I am starting the TypeScript hacks series. In this series, I will add more posts where you can practice and learn TypeScript.
This is my first post on the TypeScript hacks series. so let's get started.
Implement Pick<Type, Keys>
Constructs a type by picking the set of properties Keys from Type.
interface Todo {
title: string;
description: string;
completed: boolean;
}
If you see the above interface it has 3 properties title, description, and completed. If you want to pick some (title and completed) keys from that interface then you can use the Pick utility type. But here I am going to create a custom Pick type that will do the same thing as the Pick utility type.
type CustomPick<T, K extends keyof T> = {
[Key in K]: T[Key]
}
If you see the above code snippet which expects Type and Keys. Pick will only select keys from the Type or Interface which we are passing that's why I have return K extends keyof T
. and later we just need to check key is available in K if it's available we will return that.
type TodoPreview = Pick<Todo, "title" | "completed">;
type TodoPreviewCustomPick = CustomPick<Todo, "title" | "completed">;
Above both snippets will work the same and it will expect title and completed keys should be available when you are using that type.
For Ex.
const todo: TodoPreviewCustomPick = {
title: "Clean room",
completed: false,
};
For more details please refer official doc
Top comments (1)
Great one.