跳到主要内容

工具类型

内置工具类型各做什么?​

工具类型效果展开形式
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 等工具类型;