node_modules/typescript/lib/lib.es5.d.ts
官网:https://www.typescriptlang.org/docs/handbook/utility-types.html
同学笔记:
TS常用关键字和工具范型梳理 https://snowwolf2.yuque.com/staff-rmd8eh/gmflbs/ngchuc
TS Utils https://snowwolf2.yuque.com/staff-rmd8eh/gmflbs/ra4fve#ekml3
https://github.com/type-challenges/type-challenges
Pick
type MyPick <T, K extends keyof T> = {
[P in K]: T[P];
};
用法
https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys
解析:
function myPick (todo, keys) {
let ans = {};
for (let key of keys) {
if (key in todo) {
ans[key] = todo[key];
}
}
return ans;
}
涉及到的知识点
:::success
1.返回一个对象
2.遍历foreach mapped
https://www.typescriptlang.org/docs/handbook/2/mapped-types.html
3.todo[key] 取值indexed
https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html
4.看看key在不在todo里面
1.keyof lookup
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types
2.extends条件约束
https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints
:::
Readonly
type MyReadonly<T> = {
readonly [P in keyof T]: T[P];
}
用法
https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype
解析:
function myReadonly(todo) {
let ans = {};
for (let key in todo) {
ans[`readonly ${key}`] = todo[key];
}
return ans;
}
涉及到的知识点
:::success
1.返回一个对象
2.遍历对象
2.1in
2.2mapped keyof
2.3lookup
3.添加readonly关键字 【新知识】
4.通过key获取对应的值
:::
Tuple to Object
解析case:
- typeof 获取类型
- 字面量类型 , ex: const
- @ts-expect-error 注释
解析题目:
- 返回一个对象
- 遍历数组 P in T[number]
type TupleToObject<T extends readonly (number | string | symbol)[]> = {
[P in T[number]]: P;
}