DEV Community

Cover image for How does pick work in typescript ⛏️
Miguel
Miguel

Posted on • Updated on

How does pick work in typescript ⛏️

Hi everyone, how are you today? Hope you all are doing well!

Rick and Morty


Preface

Today we are going to understand how the pick utility works and how it is built!


Concepts

First, it is important to understand that the
Typescript is considered a
superset of Javascript, is responsible for adding static type definitions.

Types provide a way to describe the shape of objects, allowing TypeScript to verify that the code is working correctly.


To work

The pick utility builds a new type based on the set of properties chosen in the second generic position.See an example:

type Water = {
  hydrogen: number;
  oxygen: number;
};

type Electrolysis = Pick<Water, "hydrogen">;

const electrolysis: Electrolysis = {
  hydrogen: 2,
};

Enter fullscreen mode Exit fullscreen mode

In this case, we are extracting hydrogen from the water type to create a new type, in this case electrolysis

This produces an exothermic reaction. In the case of hydrogen and oxygen, the energy released is almost impossible to control, and most often leads to an explosion.


But how does the pick do it?

First, we must understand what mapping functions are.

A mapped type is a generic type that uses a union of key properties to iterate through keys to create a new type.

See an example:

example

P will interact about id and name. T[P] returns the readonly type of iterated position.

keyof produces a string or numeric literal union of keys of type.


Deconstructing the pick utility

Pick

In this case we use a generic to capture the keys we want and restrict with extends, after that we use the mapping function to traverse all K (parameters passed to generic)!

happy face

this is magic!

Time is very important, thanks for sharing a little bit of yours with me 😊.

image

image

Top comments (5)

Collapse
 
jaiko86 profile image
jaiko86

Thank you so much for this post. I got here by searching, "typescript how pick works" on Google. All the other posts talk about how to use, not how it works.

This is great. I'm going to use this knowledge, combine it with Concrete type described in this doc to create a type that guarantees a type has id prop.

Collapse
 
jaiko86 profile image
jaiko86

I actually signed in specifically to thank you.

Collapse
 
siddharthshyniben profile image
Siddharth

Hi, the explainlikeimfive tag is meant for asking questions, not for posts.

Collapse
 
un4uthorized profile image
Miguel

I made a change, thanks

Collapse
 
yanisgerst profile image
Yanis_Gerst

Hello, It should be "P in K" instead of "P in keyof T" or I miss understanding because we already sort all keys that we want with "K extends keyof T".