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']>
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.
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 .
TypeScript allows merging between multiple types such as interface with interface , enum with enum , namespace with namespace , etc.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With