TS类型体操练习
1、不使用 Pick<T, K>
,实现 TS 内置的 Pick<T, K>
的功能
从类型 T 中选出符合 K 的属性,构造一个新的类型。
例如:
interface Todo {title: stringdescription: stringcompleted: boolean
}type TodoPreview = MyPick<Todo, 'title' | 'completed'>const todo: TodoPreview = {title: 'Clean room',completed: false,
}
type MyPick<T, K> = any/* _____________ 测试用例 _____________ */
import type { Equal, Expect } from '@type-challenges/utils'type cases = [Expect<Equal<Expected1, MyPick<Todo, 'title'>>>,Expect<Equal<Expected2, MyPick<Todo, 'title' | 'completed'>>>,// @ts-expect-errorMyPick<Todo, 'title' | 'completed' | 'invalid'>,
]interface Todo {title: stringdescription: stringcompleted: boolean
}interface Expected1 {title: string
}interface Expected2 {title: stringcompleted: boolean
}
Pick<T , K>:主要用于从 Type 中选择一组属性来构造成一个新的类型。
用法:
interface Person {id: number;name: string;age: number;gender: string;phone: number;address: string;
}type PickPerson = Pick<Person, "name" | "age">
我的代码:
type MyPick<T, K extends keyof T> = {[P in K] : T[P];
}
解释:
-
K是T的子集(是从T里面选类型): K extends
-
keyof T
创建一个类型,它是T
所有公共属性键的联合。 -
映射:利用P遍历K创建属性,获取类型
T
中属性P
的类型。