Hi everyone, how are you today? Hope you all are doing well!
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,
};
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:
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
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)!
Top comments (5)
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 hasid
prop.I actually signed in specifically to thank you.
Hi, the
explainlikeimfive
tag is meant for asking questions, not for posts.I made a change, thanks
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".