How the TypeScript Pick Type works

Written by smpnjn | Published 2022/05/02
Tech Story Tags: typescript | pick-type | coding | programming | pick | data | typescript-pick-type | typescript-pick

TLDRThe TypeScript 'Pick' type is a utility type which is used to create a new custom Type, based off an already existing one. It is the opposite of the Omit Type. The type is very useful in creating custom types based on already existing ones. If you're new to custom types, [check out my guide on custom types here](https://fjolt.com/article/typescript-creating-custom-types). TypeScript has a number of utility types which are essentially custom types that solve a particular problem.via the TL;DR App

The TypeScript Pick type is a utility type which is used to create a new custom Type, based off an already existing one. It is the opposite of the Omit Type. Let's look at how it works.

Custom Types

We are using custom types in this guide. If you're new to custom types, check out my guide on custom types here.

TypeScript Pick Utility Type

TypeScript has a number of utility types which are essentially custom types that solve a particular problem. The problem which Pick solves is when we have an already existing type, and want to create a new type using only a couple of fields from that type. For example, suppose we had a User type that looks like this:

type User = {
    firstName: string,
    lastName: string,
    age: number
}

In another part of the code, we want to refer to a user, but we know that the data only gives the first and last name. As such, we can't actually use the User type as all fields are required. If we want to create a new type based off User, we can use Pick.

Pick has two arguments, the first is Type which is the type we want to use, and the second is a union type or list of fields we want to select from the type we are using. We write it like this: Type<User, "fields" | "to" | "include">. For example, let's make a new type which only has firstName and lastName:

type User = {
    firstName: string,
    lastName: string,
    age: number
}
type UserName = Pick<User, "firstName" | "lastName">

Now, using our new type, UserName, we can define a variable consisting only of firstName and lastName:

let user:UserName = {
    firstName: "John",
    lastName: "Doe"
}

If we wanted to create a new type, which only contained the user's age, we could also use Pick. Here is the example:

type User = {
    firstName: string,
    lastName: string,
    age: number
}

type UserAge = Pick<User, "age">

let age:UserAge = {
    age: 1534
}

As you can see, the Pick type is very useful in creating custom types based on already existing ones. Now that you've mastered it, you can simplify your type declarations.


Written by smpnjn | Product, Engineering, Web
Published by HackerNoon on 2022/05/02