工具类型

TypeScript 提供了一些工具类型用于实现常见的类型转换。这些工具类型是全局可用的。

Partial<Type>

构建出一个将 Type 的所有属性设置为可选属性的类型。该工具类型会返回一个代表了给定类型的所有子集的类型。

示例

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. }
  5. function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  6. return { ...todo, ...fieldsToUpdate };
  7. }
  8. const todo1 = {
  9. title: "organize desk",
  10. description: "clear clutter",
  11. };
  12. const todo2 = updateTodo(todo1, {
  13. description: "throw out trash",
  14. });

Required<Type>

构建出一个将 Type 的所有属性设置为必选属性的类型。它的作用和 Partial 相反。

示例

  1. interface Props {
  2. a?: number;
  3. b?: string;
  4. }
  5. const obj: Props = { a: 5 };
  6. const obj2: Required<Props> = { a: 5 };
  7. ^
  8. // Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly<Type>

构建出一个将 Type 的所有属性设置为只读属性的类型,这意味着构造出来的类型的属性不可以重新被赋值。

示例

  1. interface Todo {
  2. title: string;
  3. }
  4. const todo: Readonly<Todo> = {
  5. title: "Delete inactive users",
  6. };
  7. todo.title = "Hello";
  8. ^
  9. // Cannot assign to 'title' because it is a read-only property.

这个工具类型可以有效地表示会在运行时失败(比如试图给冻结对象的属性重新赋值)的赋值表达式。

Object.freeze

  1. function freeze<Type>(obj: Type): Readonly<Type>;

Record<Keys,Type>

构建出一个对象类型,它的属性键是 Keys,属性值是 Type。该工具类型可以将属性从某个类型映射为另一种类型。

示例

  1. interface CatInfo {
  2. age: number;
  3. breed: string;
  4. }
  5. type CatName = "miffy" | "boris" | "mordred";
  6. const cats: Record<CatName, CatInfo> = {
  7. miffy: { age: 10, breed: "Persian" },
  8. boris: { age: 5, breed: "Maine Coon" },
  9. mordred: { age: 16, breed: "British Shorthair" },
  10. };
  11. cats.boris;
  12. ^
  13. // const cats: Record<CatName, CatInfo>

Pick<Type,Keys>

Type 中挑出属性集 Keys(字符串字面量或者字符串字面量的联合类型),从而构建类型。

示例

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. }
  6. type TodoPreview = Pick<Todo, "title" | "completed">;
  7. const todo: TodoPreview = {
  8. title: "Clean room",
  9. completed: false,
  10. };
  11. todo;
  12. ^
  13. // const todo: TodoPreview

Omit<Type,Keys>

Type 中挑出所有属性并移除 Keys(字符串字面量或者字符串字面量的联合类型),从而构建类型。

示例

  1. interface Todo {
  2. title: string;
  3. description: string;
  4. completed: boolean;
  5. createdAt: number;
  6. }
  7. type TodoPreview = Omit<Todo, "description">;
  8. const todo: TodoPreview = {
  9. title: "Clean room",
  10. completed: false,
  11. createdAt: 1615544252770,
  12. };
  13. todo;
  14. ^
  15. // const todo: TodoPreview
  16. type TodoInfo = Omit<Todo, "completed" | "createdAt">;
  17. const todoInfo: TodoInfo = {
  18. title: "Pick up kids",
  19. description: "Kindergarten closes at 5pm",
  20. };
  21. todoInfo;
  22. ^
  23. // const todoInfo: TodoInfo

Exclude<Type,ExcludedUnion>

Type 中排除所有可以赋值给 ExcludedUnion 的联合类型成员。

示例

  1. type T0 = Exclude<"a" | "b" | "c", "a">;
  2. ^
  3. // type T0 = "b" | "c"
  4. type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
  5. ^
  6. // type T1 = "c"
  7. type T2 = Exclude<string | number | (() => void), Function>;
  8. ^
  9. // type T2 = string | number

Extract<Type,Union>

Type 中提取出所有可以赋值给 Union 的联合类型成员,从而构建类型。

示例

  1. type T0 = Extract<"a" | "b" | "c", "a" | "f">;
  2. ^
  3. // type T0 = "a"
  4. type T1 = Extract<string | number | (() => void), Function>;
  5. ^
  6. // type T1 = () => void

NonNullable<Type>

Type 中排除 nullundefined,从而构建类型。

示例

  1. type T0 = NonNullable<string | number | undefined>;
  2. ^
  3. // type T0 = string | number
  4. type T1 = NonNullable<string[] | null | undefined>;
  5. ^
  6. // type T1 = string[]

Parameters<Type>

从函数类型 Type 的参数使用的类型中构建一个元组类型。

示例

  1. declare function f1(arg: { a: number; b: string }): void;
  2. type T0 = Parameters<() => string>;
  3. ^
  4. // type T0 = []
  5. type T1 = Parameters<(s: string) => void>;
  6. ^
  7. // type T1 = [s: string]
  8. type T2 = Parameters<<T>(arg: T) => T>;
  9. ^
  10. // type T2 = [arg: unknown]
  11. type T3 = Parameters<typeof f1>;
  12. ^
  13. /*
  14. type T3 = [arg: {
  15. a: number;
  16. b: string;
  17. }]
  18. */
  19. type T4 = Parameters<any>;
  20. ^
  21. // type T4 = unknown[]
  22. type T5 = Parameters<never>;
  23. ^
  24. // type T5 = never
  25. type T6 = Parameters<string>;
  26. ^
  27. // Type 'string' does not satisfy the constraint '(...args: any) => any'.
  28. // type T6 = never
  29. type T7 = Parameters<Function>;
  30. ^
  31. /*
  32. Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  33. Type 'Function' provides no match for the signature '(...args: any): any'.
  34. type T7 = never
  35. */

ConstructorParameters<Type>

从一个构造函数类型的类型中构建一个元组或者数组类型。它会通过所有的参数类型产生一个元组类型(或者,如果 Type 不是函数,则返回 never 类型)。

示例

  1. type T0 = ConstructorParameters<ErrorConstructor>;
  2. ^
  3. // type T0 = [message?: string]
  4. type T1 = ConstructorParameters<FunctionConstructor>;
  5. ^
  6. // type T1 = string[]
  7. type T2 = ConstructorParameters<RegExpConstructor>;
  8. ^
  9. // type T2 = [pattern: string | RegExp, flags?: string]
  10. type T3 = ConstructorParameters<any>;
  11. ^
  12. // type T3 = unknown[]
  13. type T4 = ConstructorParameters<Function>;
  14. ^
  15. /*
  16. Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
  17. Type 'Function' provides no match for the signature 'new (...args: any): any'.
  18. type T4 = never
  19. */

ReturnType<Type>

构建一个由函数 Type 的返回值类型组成的类型。

示例

  1. declare function f1(): { a: number; b: string };
  2. type T0 = ReturnType<() => string>;
  3. ^
  4. // type T0 = string
  5. type T1 = ReturnType<(s: string) => void>;
  6. ^
  7. // type T1 = void
  8. type T2 = ReturnType<<T>() => T>;
  9. ^
  10. // type T2 = unknown
  11. type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
  12. ^
  13. // type T3 = number[]
  14. type T4 = ReturnType<typeof f1>;
  15. ^
  16. /*
  17. type T4 = {
  18. a: number;
  19. b: string;
  20. }
  21. */
  22. type T5 = ReturnType<any>;
  23. ^
  24. // type T5 = any
  25. type T6 = ReturnType<never>;
  26. ^
  27. // type T6 = never
  28. type T7 = ReturnType<string>;
  29. ^
  30. // Type 'string' does not satisfy the constraint '(...args: any) => any'.
  31. // type T7 = any
  32. type T8 = ReturnType<Function>;
  33. ^
  34. /*
  35. Type 'Function' does not satisfy the constraint '(...args: any) => any'.
  36. Type 'Function' provides no match for the signature '(...args: any): any'.
  37. type T8 = any
  38. */

ThisParameterType<Type>

从一个函数类型中提取出 this 参数的类型,或者在函数类型没有 this 参数的情况下提取出 unknown 类型。

示例

  1. function toHex(this: Number) {
  2. return this.toString(16);
  3. }
  4. function numberToString(n: ThisParameterType<typeof toHex>) {
  5. return toHex.apply(n);
  6. }

OmitThisParameter<Type>

Type 中移除 this 参数。如果 Type 没有显式声明 this 参数,那么直接返回 Type,否则会基于 Type 创建一个没有 this 参数的新的函数类型。泛型会被抹除,并且只有最后一个重载签名会传播到新的函数类型中。

示例

  1. function toHex(this: Number) {
  2. return this.toString(16);
  3. }
  4. const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);
  5. console.log(fiveToHex());

ThisType<Type>

这个工具类型并没有返回一个被转化的类型,而是作为一个上下文 this 类型的标记。注意,必须在启用 noImplicitThis 配置项之后才能使用该工具类型。

示例

  1. type ObjectDescriptor<D, M> = {
  2. data?: D;
  3. methods?: M & ThisType<D & M>; // methods 中 this 的类型是 D & M
  4. };
  5. function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M {
  6. let data: object = desc.data || {};
  7. let methods: object = desc.methods || {};
  8. return { ...data, ...methods } as D & M;
  9. }
  10. let obj = makeObject({
  11. data: { x: 0, y: 0 },
  12. methods: {
  13. moveBy(dx: number, dy: number) {
  14. this.x += dx; // Strongly typed this
  15. this.y += dy; // Strongly typed this
  16. },
  17. },
  18. });
  19. obj.x = 10;
  20. obj.y = 20;
  21. obj.moveBy(5, 5);

在上面的示例中,传给 makeObject 的参数中的 methods 对象有一个包含 ThisType<D & M> 的上下文类型,因此在 methods 对象的方法中,this 的类型是 { x: number, y: number } & { moveBy(dx: number, dy: number): number }。注意 methods 属性的类型既是一个推断目标,也是方法中 this 类型的来源。

ThisType<T> 标记接口只是一个在 lib.d.ts 中声明的空接口。除了在一个对象字面量的上下文类型中被识别之外,它的表现和任何的空接口一样。

内置的字符串操控类型

Uppercase<StringType>

Lowercase<StringType>

Capitalize<StringType>

Uncapitalize<StringType>

为了方便操控模板字符串字面量,TypeScript 引入了一系列可以在类型系统的字符串操控中使用的类型。你可以在文档的模板字面量类型中找到这些工具类型。