58

I use Pick, but how could I write a generic PickMulti which can pick multiple fields?

interface MyInterface {
  a: number,
  b: number,
  c: number
}

// this works, but I would like a generic one in number of fields
type AB = Pick<Pick<MyInterface, 'a'>, 'b'>;

// Something like this:
type PickMulti = /* how to write this?*/;
type AB = PickMulti<MyInterface, ['a', 'b']>

3 Answers 3

114

Pick already works with multiple fields you just need to provide them as a union, not a tuple/array type:

interface MyInterface {
  a: number,
  b: number,
  c: number
}

type AB = Pick<MyInterface, 'a' | 'b'>;

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

-1

You may want to work with arrays as in your example:

type PickMulti = /* how to write this?*/;
type AB = PickMulti<MyInterface, ['a', 'b']>

So if you have array:

const fields = Object.keys(object).filter(...)
// or
const fields = ['a', 'b']

It may be solved like this:

const pickArray = [...fields] as const;
type pickUnion = typeof pickArray[number];
type PickAB = Pick<MyInterface, pickUnion & keyof MyInterface>;

Comments

-1

You can try something like this

type PickMulti<T, K extends (keyof T)[]> = {
      [Key in K[number]]: T[Key];
    };

type AB = PickMulti<MyInterface, ['a', 'b']>

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.