The Pick type is used to simplify type generation when you want to construct a type by picking keys from a specific interface.
Below, by using the Pick type, a new type is created that only contains the `firstName` and `lastName` properties.
```typescript
interface IPerson {
firstName: string;
lastName: string;
age: number;
}
type PersonFullName = Pick<IPerson, 'firstName' | 'lastName'>;
const person: PersonFullName = { firstName: 'Tim', lastName: 'Mousk' };
```
For another example, say an application has an interface IUser and there's a need to create an authentication function that accepts an object that uses some fields from the IUser interface.
```typescript
interface IUser {
userName: string;
firstName: string;
lastName: string;
password: string;
role: string;
age: number;
}
type PersonCredentials = Pick<IUser, 'userName' | 'password'>;
```
If for example, a property is changed in the IUser interface, the TypeScript Intellisense will show an error, since the property does not exist anymore.
### Using Pick on a nested object
Keys can be picked from the interface by using indexes:
```typescript
interface IPerson {
firstName: string;
lastName: string;
age: number;
address: {
country: string;
city: string;
street: string;
}
}
type Person = Pick<IPerson, 'firstName' | 'lastName'> & {
address: Array<Pick<IPerson['address'], 'city' | 'street'>>
}
```
### Using Pick and making properties optional
```typescript
interface IPerson {
firstName: string;
lastName: string;
age: number;
}
type CopyWithPartial<T, K extends keyof T> = Omit<T, K> & Partial<T>;
type PartialPerson = CopyWithPartial<IPerson, 'firstName' | 'lastName'>;
const person: PartialPerson = { firstName: 'Tim' };
```
#### More info
___
**Tags**: #typescript #pick