Alo
Alo

Alo

`Pick<Type, Keys>` in TypeScript

Photo by S&B Vonlanthen on Unsplash

`Pick<Type, Keys>` in TypeScript

Alo's photo
Alo
ยทApr 12, 2022ยท

2 min read

This article is part of the Series: Typescript utility types, in plain English

Pick in a nutshell ๐Ÿฅœ

Pick is a very useful utility type. It allows you to create a new type by selecting only certain properties.

Each key is delimited by the 'pipe' operator |

type User = {
    id: number,
    firstName:string,
    lastName:string,
    email: string,
    dob: Date,
    hobbies: [/*...*/],
    /*
        And a lot more properties
    */
}

type Badge = Pick<User, 'firstName'| 'lastName'>

/* 
Equivalent to

type Bagdge = {
    firstName: string,
    lastName:string,
}
*/

Example โœ๏ธ

When should you use Pick?

I can see two scenarios

When you only need certain properties

The example above is a good example: a User badge should only contain its firstName and lastName. In that case, Pick<Type, Keys> is the way to go.

As a way to combine utility types:

Pick<Type,Keys> is an excellent 'combinator'.

Remember our Partial<Type> utility type? It made properties of the type optional. That's great, but how can we only make certain properties partial? By combining utility types.

Now, we're getting into the real power of utility types.

Combining utility types: unleashing the power of utility types ๐Ÿช„

This is my opinion, where all the power of utility type resides.

Let's say we have a flight booking application. When booking your ticket, you can provide the email address of another user to keep her/him updated about your flight's details.

How could we model this?

// We already have our `User` model
type User = {
    firstName: string,
    lastName: string,
    phoneNumber: string,
    email: string,
}

type FlightBookingForm = {
    customer: User // The person booking you the ticket
    userToInform: Partial<Pick<User, "email">>
}

/*
    This is equivalent to:

    type FlightBookingForm = {
        customer: User,
        userToInform: {
            email?: string
        }
    }
*/

Conclusion โ˜๏ธ

Pick<Type, Keys> is yet another commonly used utility type, useful to 'cherry-pick' the properties you are interested in. I am starting to repeat myself a lot here, but as you can see: it's easy peasy to use.

We have also seen another very powerful tool: combining utility types.

By combining utility types you are unleashing the power of utility types to create new powerful types.

In the next articles, we will continue to explore utility types and how you can combine them together. Stay tuned

ย 
Share this