Pick

This lesson explains the pick mapped type.

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:

Press + to interact
// An interface that defines fields for an Animal
interface Animal {
age: number;
numberOfLegs: number;
canSwim: boolean;
runningSpeed: number;
name: string;
}
// An interface that defines fields for a Fish
interface 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.

Press + to interact
// An Animal has all fields from Fish
interface Animal extends Fish{
numberOfLegs: number;
canSwim: boolean;
runningSpeed: number;
}
// Fish schema
interface 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 ...