Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Same as Pick<...>, but with multiple fields

Tags:

typescript

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']>
like image 306
jeanpaul62 Avatar asked Dec 03 '19 16:12

jeanpaul62


People also ask

Why use Pick in TypeScript?

In TypeScript, pick is used to take the certain objects of an already defined interface to create a new model. Pick is used a bit differently from the other utilities of TypeScript.

What is Pick in Ts?

Pick is what's known as a Mapped Type, and I've covered other Mapped Types in my TypeScript Masterclass course. Here's the syntax for Pick : Pick<Type, Keys> We pass in an existing Type and then declare the Keys we wish to “pick” from the Type .

Is it possible to combine types in TS?

TypeScript allows merging between multiple types such as interface with interface , enum with enum , namespace with namespace , etc.

What is ampersand in TypeScript?

A & in TS in the context of a types means an intersection type. It merges all properties of 2 object types together and creates a new type.


1 Answers

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

like image 67
Titian Cernicova-Dragomir Avatar answered Oct 20 '22 01:10

Titian Cernicova-Dragomir