定义:从联合类型 T 中剔除所有可赋值给 U 的成员,返回剩余联合。
语法:
type Exclude<T, U> = T extends U ? never : T;
示例:
type A = "a" | "b" | "c";
type B = Exclude<A, "a" | "b">; // B = "c"
定义:从联合类型 T 中提取所有可赋值给 U 的成员。
语法:
type Extract<T, U> = T extends U ? T : never;
示例:
type A = string | number | boolean;
type B = Extract<A, string | boolean>; // B = string | boolean
定义:从类型 T 中剔除 null 和 undefined 。
语法:
type NonNullable<T> = Exclude<T, null | undefined>;
示例:
type A = string | null | undefined;
type B = NonNullable<A>; // B = string
定义:构造一个对象类型,其键集为 K,值类型为 T。
语法:
type Record<K extends keyof any, T> = {
[P in K]: T
}
示例:
type Cities = "beijing" | "shanghai";
type CityInfo = Record<Cities, { population: number }>;
// 相当于:
// {
// beijing: { population: number };
// shanghai: { population: number };
// }