1.可选泛型

将泛型中的所有属性变为可选.

type Partial<T> = {
[P in keyof T]?: T[P]
};

举例:

type Person = {
name: string;
age: number;
gender: string;
height: number;
weight: number;
};

再使用Partial包裹

type PartOfPerson = Partial<Person>;

const ben: PartOfPerson = {
name: 'Ben',
age: 18,
};


2.将K类型的所有属性转换为T类型

type Record<K extends keyof any, T> = {
[P in K]: T;
};

这里的K实际作为键值使用,所以仅可用number|string|symbol类型

举例:

const obj: Record<string, string | number> = {
name: 'zhangsan',
age: 18,
weight: 80,
gender: '男',
};
interface CatInfo {
age: number;
breed: string;
}

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};


3.从T类型中提取K的键值列出来组成新的类型

type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};

举例:定义一个人的类型

type Person = {
name: string;
age: number;
gender: string;
height: number;
weight: number;
};

重新定义一个只有名字和年龄的类型

type NewPerson = Pick<Person, 'name' | 'age'>;

const Mike: NewPerson = {
name: 'mike',
age: 20,
};


4.去除T类型和U类型中的交集,取剩余部分

type Exclude<T, U> = T extends U ? never : T;

举例:

type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T2 = Exclude<string | number | (() => void), Function | string>; // "number"


5.去除T类型中包含的K键值对

type Omit = Pick<T, Exclude<keyof T, K>>

举例:

type Person = {
name: string;
age: number;
gender: string;
height: number;
weight: number;
};

去除Person类型中的heightweight属性

type NewPerson = Omit<Person, 'height' | 'age'>;

const Mike: NewPerson = { name: 'Mike', age: 18, gender: '男' };


6.将类型T中的所有属性变为必选项

type Required<T> = {
[P in keyof T]-?: T[P]
}

举例:

type Person = {
name: string;
age: number;
gender: string;
height?: number;
weight?: number;
};

将Person中的height和weight属性变为必选项目

type AllPerson = Required<Person>;

const Mike: AllPerson = {
name: 'Mike',
age: 18,
gender: '男',
height: 180,
weight: 80,
};


7.获取T类型对应的返回值类型

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;


8.总结

工具 特征
Partial<T> 将类型中全部属性变为可选的
Required<T> 将类型T中的所有属性变为必选项
Record<K, T> 将K类型的所有属性转换为T类型
Pick<T, K> 从T类型中提取K的键值列出来组成新的类型
Exclude<T, U> 去除T类型和U类型中的交集,取剩余部分
Omit<T, K> 去除T类型中包含的K键值对
ReturnType<T> 获取T类型(函数)对应的返回值类型
Readonly<T> 将类型T中所有属性变为只读
Extract<T,K> 取T类型和K类型的交集组成新的类型
NonNullable<T> 去除T类型中的null和undefined类型