TypeScript 实用工具类型

TypeScript 提供了大量的类型,可以帮助进行一些常见的类型操作,这些类型通常被称为实用工具类型。

本章将介绍最受欢迎的实用工具类型。

Partial

Partial 将对象中的所有属性变为可选。

实例

interface Point {
  x: number;
  y: number;
}

let pointPart: Partial<Point> = {}; // 'Partial' 允许 x 和 y 为可选
pointPart.x = 10;

亲自试一试

Required

Required 将对象中的所有属性变为必填。

实例

interface Car {
  make: string;
  model: string;
  mileage?: number;
}

let myCar: Required<Car> = {
  make: 'Ford',
  model: 'Focus',
  mileage: 12000 // 'Required' 强制定义 mileage
};

亲自试一试

Record

Record 是定义具有特定键类型和值类型的对象类型的快捷方式。

实例

const nameAgeMap: Record<string, number> = {
  'Alice': 21,
  'Bob': 25
};
Record<string, number> is equivalent to { [key: string]: number }

亲自试一试

Omit

Omit 从对象类型中移除键。

实例

interface Person {
  name: string;
  age: number;
  location?: string;
}

const bob: Omit<Person, 'age' | 'location'> = {
  name: 'Bob'
  // 'Omit' 已从类型中移除了 age 和 location,因此不能在此处定义它们
};

亲自试一试

Pick

Pick 从对象类型中仅保留指定的键,移除其他所有键。

实例

interface Person {
  name: string;
  age: number;
  location?: string;
}

const bob: Pick<Person, 'name'> = {
  name: 'Bob'
  // 'Pick' 仅保留了 name,因此从类型中移除了 age 和 location,不能在此处定义它们
};

亲自试一试

Exclude

Exclude 从联合类型中移除类型。

实例

type Primitive = string | number | boolean
const value: Exclude<Primitive, string> = true; // 由于 Exclude 将其从类型中移除,因此此处不能使用字符串。

亲自试一试

ReturnType

ReturnType 提取函数类型的返回类型。

实例

type PointGenerator = () => { x: number; y: number; };
const point: ReturnType<PointGenerator> = {
  x: 10,
  y: 20
};

亲自试一试

Parameters

Parameters 提取函数类型的参数类型作为数组。

实例

type PointPrinter = (p: { x: number; y: number; }) => void;
const point: Parameters<PointPrinter>[0] = {
  x: 10,
  y: 20
};

亲自试一试

Readonly

Readonly 用于创建一个新类型,其中所有属性都是只读的,这意味着一旦为它们分配了值,就无法修改它们。

请记住,TypeScript 将在编译时阻止这种情况,但从理论上讲,由于它被编译为 JavaScript,您仍然可以覆盖只读属性。

实例

interface Person {
  name: string;
  age: number;
}
const person: Readonly<Person> = {
  name: "Dylan",
  age: 35,
};
person.name = 'Israel'; // prog.ts(11,8): 错误 TS2540: 无法分配给 'name',因为它是只读属性。

亲自试一试