Easy
Based on
- https://github.com/type-challenges/type-challenges
- https://ghaiklor.github.io/type-challenges-solutions/en/
Pick
สร้าง Type ใหม่ โดยเลือก key จาก K จาก object T (โดยปกติ TypeScript จะมี built-in Pick<T, K> อยู่แล้ว)
For example:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = MyPick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
Explanation
type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
};
สร้าง Type ที่ชื่อ MyPick โดยที่มี parameter เป็น T และ K ซึ่ง K เป็น type keyof T เท่านั้น
สมมติ T เป็น Todo ดังนั้น keyof T จะเป็น type 'title' | 'description' | 'completed'
ในส่วนของการ return type ({ [P in K]: T[P] })หมายถึงให้สร้าง Mapped Types โดยที่มี
- Key (
[P in K]): หมายถึงการ ForeachPinK- ในโจทย์
Kคือ"title" | "completed" - ดังนั้น
Pจะมีได้ 2 ค่า คือtitleและcompleted
- ในโจทย์
- Value (
T[P]): เป็น Lookup TypesT[P]โดยเอาPที่มาจากการ Foreach ใน Key ไป โดยเอา Type จากT[P]- ถ้า
Pเป็น "title" ดังนั้นT[P]คือ string - ถ้า
Pเป็น "completed" ดังนั้นT[P]คือ boolean
- ถ้า
อ่านเพิ่ม
References
Readonly
สร้าง Type ใหม่ เพื่อแปลงให้ทุก key ของ object เป็น readonly หรือก็คือ ไม่สามารถ Assign (โดยปกติ TypeScript จะมี built-in Readonly<T> อยู่แล้ว)
For example:
interface Todo {
title: string;
description: string;
}
const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar",
};
todo.title = "Hello"; // Error: cannot reassign a readonly property
todo.description = "barFoo"; // Error: cannot reassign a readonly property
Explanation
type MyReadonly<T> = {
readonly [K in keyof T]: T[K]
};