Pick
This lesson explains the pick mapped type.
We'll cover the following...
Description of Pick
The Pick mapped type is a new addition that comes with TypeScript and it allows you to select a subset of a type’s properties in order to create a dynamic type.
If a type has five members and you only need two of them, there are many possible patterns. Without a mapped type, you have two options. The first one is to create two different types like so:
// An interface that defines fields for an Animalinterface Animal {age: number;numberOfLegs: number;canSwim: boolean;runningSpeed: number;name: string;}// An interface that defines fields for a Fishinterface Fish {age: number;name: string;}
The inheritance problem #
The problem with that approach is the duplication of two members (age and name). The second option is to use inheritance.
// An Animal has all fields from Fishinterface Animal extends Fish{numberOfLegs: number;canSwim: boolean;runningSpeed: number;}// Fish schemainterface Fish {age: number;name: string;}
Improvement of the inheritance solution
Inheritance works well, but it needs to be built smartly, which was not the case in the previous block of code. This has been done on purpose to illustrate that an Animal is not a Fish but technically, it helps us to not have the members repeated. A better inheritance ...