Pick
介绍
不使用 Pick<T, K>
,实现 TS 内置的 Pick<T, K>
的功能。
从类型 T
中选出符合 K
的属性,构造一个新的类型。
例如:
ts
interface Todo {title: string;description: string;completed: boolean;}type MyPick<T, K> = any;type TodoPreview = MyPick<Todo, 'title' | 'completed'>;const todo: TodoPreview = {title: 'Clean room',completed: false,};
View on GitHubts
interface Todo {title: string;description: string;completed: boolean;}type MyPick<T, K> = any;type TodoPreview = MyPick<Todo, 'title' | 'completed'>;const todo: TodoPreview = {title: 'Clean room',completed: false,};
起点
ts
/* _____________ Your Code Here _____________ */typeMyPick <T ,K > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Expected1 ,MyPick <Todo , 'title'>>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Expected2 ,MyPick <Todo , 'title' | 'completed'>>>,// @errors: 2344MyPick <Todo , 'title' | 'completed' | 'invalid'>];interfaceTodo {title : string;description : string;completed : boolean;}interfaceExpected1 {title : string;}interfaceExpected2 {title : string;completed : boolean;}
Take the Challengets
/* _____________ Your Code Here _____________ */typeMyPick <T ,K > = any;/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Expected1 ,MyPick <Todo , 'title'>>>,Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.Expect <Equal <Expected2 ,MyPick <Todo , 'title' | 'completed'>>>,// @errors: 2344MyPick <Todo , 'title' | 'completed' | 'invalid'>];interfaceTodo {title : string;description : string;completed : boolean;}interfaceExpected1 {title : string;}interfaceExpected2 {title : string;completed : boolean;}
解决方案
点击展开答案
ts
typeMyPick <T ,K extends keyofT > = {[Key inK ]:T [Key ];};// 测试用例中的@ts-expect-error不会生效,所以会报错typeMyPick2 <T ,K > = {[P in keyofT asP extendsK ?P : never]:T [P ]};// 执行会报错, 和上面相同的原因typeMyPick3 <T ,K > = {[P inK & keyofT ]:P extendsT ?T [P ] : never};
ts
typeMyPick <T ,K extends keyofT > = {[Key inK ]:T [Key ];};// 测试用例中的@ts-expect-error不会生效,所以会报错typeMyPick2 <T ,K > = {[P in keyofT asP extendsK ?P : never]:T [P ]};// 执行会报错, 和上面相同的原因typeMyPick3 <T ,K > = {[P inK & keyofT ]:P extendsT ?T [P ] : never};