要求:实现TS内置的Pick<T,K> 从类型T中选择出属性K,构造一个新的类型
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
}
js实现思路:
- 返回一个对象
- 遍历forEach
-
T[item]取值
-
看看item在不在T中
js实现:
function MyPick(T,K){const obj={}K.forEach(item=>(if(item in T){ //T 中是否有 item 属性obj[item]=T[item]}))return obj;}
ts实现: 【模仿js实现思路实现】
- 返回一个对象
- 遍历forEach mapped
-
T[item]取值 indexed
-
看看item在不在T中 keyof
type MyPick<T, K extends keyof T> = {[P in K]:T[P]
}
题目:type-challenges/README.zh-CN.md at main · type-challenges/type-challenges · GitHubCollection of TypeScript type challenges with online judge - type-challenges/README.zh-CN.md at main · type-challenges/type-challengeshttps://github.com/type-challenges/type-challenges/blob/main/questions/00004-easy-pick/README.zh-CN.md
学习:
TypeScript: Handbook - The TypeScript Handbookhttps://www.typescriptlang.org/docs/handbook/intro.html