TypeScript 工具类型
TypeScript 附带了大量类型,可以帮助进行一些常见的类型操作,通常称为工具类型(实用类型)。
本章介绍了最流行的工具类型(Utility Type)。
Partial
Partial 更改对象中的所有属性为可选。
实例
interface Point {x: number;y: number;}let pointPart: Partial<point> = {}; // `Partial` 使得 x 与 y 都变成可选pointPart.x = 10;console.log(pointPart);
Required
Required 更改对象中的所有属性为必须的。
实例
interface Car {make: string;model: string;mileage?: number;}let myCar: Required<car> = {make: 'Ford',model: 'Focus',mileage: 12000 // `Required` 强制 mileage 必须定义};console.log(myCar);
Record
Record 是定义具有特定键类型和值类型的对象类型的简写方式。
实例
const nameAgeMap: Record<string, number=""> = {'Alice': 21,'Bob': 25};console.log(nameAgeMap);
Record<string, number> 相当于 { [key: string]: number }Omit
Omit 从对象类型中删除 key。
实例
interface Person {name: string;age: number;location?: string;}const bob: Omit<person, 'age'="" |="" 'location'=""> = {name: 'Bob'// `Omit` 已从类型中删除了 age 和 location,无法在此处定义};console.log(bob);
Pick
Pick 从对象类型中删除除指 key 以外的所有 key。
实例
interface Person {name: string;age: number;location?: string;}const bob: Pick<person, 'name'=""> = {name: 'Bob'// `Pick` 只保留了 name,因此 age 和 location 已从类型中删除,无法在此处定义};console.log(bob);
Exclude
Exclude 从联合类型中删除类型。
实例
type Primitive = string | number | boolean;const value: Exclude<primitive, string=""> = true;// 此处不能使用 string,因为 Exclude 将其从类型中删除。console.log(typeof value);
ReturnType
ReturnType 提取函数类型的返回类型。
实例
type PointGenerator = () => { x: number; y: number; };const point: ReturnType<pointgenerator> = {x: 10,y: 20};
参数
Parameters 将函数类型的参数类型提取为数组。
实例
type PointPrinter = (p: { x: number; y: number; }) => void;const point: Parameters<pointprinter>[0] = {x: 10,y: 20};