跳到主要内容

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,
};
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 GitHub

起点

ts
/* _____________ Your Code Here _____________ */
type MyPick<T, K> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
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'>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
// @errors: 2344
MyPick<Todo, 'title' | 'completed' | 'invalid'>
];
 
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
interface Expected1 {
title: string;
}
 
interface Expected2 {
title: string;
completed: boolean;
}
ts
/* _____________ Your Code Here _____________ */
type MyPick<T, K> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
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'>>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
// @errors: 2344
MyPick<Todo, 'title' | 'completed' | 'invalid'>
];
 
interface Todo {
title: string;
description: string;
completed: boolean;
}
 
interface Expected1 {
title: string;
}
 
interface Expected2 {
title: string;
completed: boolean;
}
Take the Challenge

解决方案

点击展开答案
ts
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key];
};
// 测试用例中的@ts-expect-error不会生效,所以会报错
type MyPick2<T,K> = {
[P in keyof T as P extends K ? P : never]: T[P]
};
// 执行会报错, 和上面相同的原因
type MyPick3<T,K> = {
[P in K & keyof T]: P extends T ? T[P] : never
};
ts
type MyPick<T, K extends keyof T> = {
[Key in K]: T[Key];
};
// 测试用例中的@ts-expect-error不会生效,所以会报错
type MyPick2<T,K> = {
[P in keyof T as P extends K ? P : never]: T[P]
};
// 执行会报错, 和上面相同的原因
type MyPick3<T,K> = {
[P in K & keyof T]: P extends T ? T[P] : never
};
Checkout more Solutions