快速了解TypeScirpt工具类
秋招字节第一面就问到了ts工具类中的Record,当时才刚接触ts不久,人都懵了。遂发文记录下稍微复杂点的工具类学习记录
/**
* 参考文章: https://juejin.cn/post/6994102811218673700#heading-3
*/
interface Eg1 {
name: string;
readonly age: number;
}
// Partial 将T的所有属性变成可选的。
type _Partial = {
/* 通过映射类型,遍历T上的所有属性 */ [P in keyof T]?: T[P] /* 设置类型为原来的类型 */;
};
// Readonly 遍历T的key添加readonly修饰符 略
// Pick 挑选T中的key组成新类型 略
// Reacord<> 将一组key的类型都设为T
type _Record = {
[P in K]: T;
};
/**
* @example Record举例
* type Eg01 = {
* j: Eg1;
* z: Eg1;
* }
*/
type Eg01 = _Record;
// 扩展: 同态与非同态。Partial、Readonly和Pick都属于同态的,即会拷贝 readonly和?:的修饰符。Record 则不会
// Exclude 把T中类型束于U(存在于U、兼容于U)的类型排除掉(被置为never),Extract是保留约束于U的
type _Exclude = T extends U ? never : T;
/**
* @example
* type Eg = "key1" | "a"
*/
type Eg = _Exclude<"key1" | "key2" | "a", "key2" | "b">;
//Omit 把T中K剔除掉,利用Pick提取需要的keys组成的类型
type _Omit = Pick>;
// 获得函数的参数类型,并存到命名元组中(命名只是提供语义化), ReturnType 就是获取函数返回类型并存到元组中
type Eg22 = Parameters<(arg1: string, arg2: number) => void>;
// ConstructorParameters<> 获取类的构造函数的参数类型并存到元组