Typescript Series - Pick Utility Type
Sarmun Bustillo
Posted on August 15, 2022
I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.
What is the Pick Utility Type?
Pick <Type, Keys>
Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type. In other words, the new type is a subgroup of properties that are extracted from Type properties Docs.
This is how it works:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
So as you can see, we picked only the 2 keys we wanted from the Todo Type Preview.
But how does it work under the hood?
type Pick<Type, Key extends keyof Type> = {
[k in Key]: Type[k];
};
So let's break down the tricky parts.
Key extends keyof Type
The keyword extends in this case means Key should exist in its parent, wherein keyof Type is the parent. If we were to take the Todo interface from above as an example, the keys would be "title" | "description" | "completed"
[k in Key]
The keyword in means that K has to be one of the keys extracted from Key ("title" | "description" | "completed")
Type[k]
Finally, here we are simply accessing the type of a property. Same as how we access values in an object, let's look at the following example.
interface Person {
name: string;
age: number;
}
// Access the type of name
Person['name'] // string
// Like saying Type[K] where Type is Person and name is K
Well, there you have it, now you know how the Pick utility type works!
Conclusion
The Pick utility type it's very handy since it allows us to dynamically construct new types from existing ones,
Thank you!
you can find me here My Twitter
Posted on August 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 16, 2024