工具类型
内置工具类型各做什么?
| 工具类型 | 效果 | 展开形式 |
|---|---|---|
Partial<T> | 所有属性变为可选 | { [P in keyof T]?: T[P] } |
Required<T> | 所有属性变为必选 | { [P in keyof T]-?: T[P] } |
Readonly<T> | 所有属性变为只读 | { readonly [P in keyof T]: T[P] } |
Pick<T, K> | 只保留指定属性 | { [P in K]: T[P] } |
Omit<T, K> | 移除指定属性 | Pick<T, Exclude<keyof T, K>> |
Record<K, T> | 生成键为 K、值为 T 的对象 | { [P in K]: T } |
Exclude<T, U> | 从联合类型中排除指定类型 | 条件类型按成员过滤 |
type PersonPartial = Partial<Person>;
type RequiredContact = Required<Contact>;
type ReadonlyPerson = Readonly<Person>;
type ContactPick = Pick<Contact, "name" | "phone">;
type OmitEmailContact = Omit<Contact, "email">;
type Fruit = "apple" | "banana" | "orange";
type Inventory = Record<Fruit, number>;
type Platform = "Windows" | "MacOS" | "Linux" | "iOS" | "Android";
type DesktopPlatform = Exclude<Platform, "iOS" | "Android">;
条件类型如何按条件选择类型?
- 语法:
T extends U ? X : Y; - 判定:
T能赋值给U时取X, 否则取Y;
declare function f<T extends boolean>(x: T): T extends true ? string : number;
const x = f(Math.random() < 0.5); // x: string | number
- 用途: 让返回类型随类型参数变化, 以及实现
Exclude、Omit等工具类型;