前言

上一节我们封装了一些类型演算
本节课介绍的就是 ts 中自带的一些类型演算

关键字
Utility Types(类型演算、类型工具)

参考资料

  1. Utility Types:链接

    notes

Utility Types
TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
TypeScript 提供了一些类型工具促成常见的类型转换。这些工具可以在全局环境中访问。

Utility Types 描述
Partial 将类型 T 中的成员变为可选
Required 将类型 T 中的成员变为必填
Readonly 将类型 T 中的成员变为只读
Exclude 从 T 中剔除可以赋值给 U 的类型
Extract 提取 T 中可以赋值给 U 的类型
NonNullable 从 T 中剔除 null 和 undefined
ReturnType 获取函数返回值类型
InstanceType 获取构造函数类型的实例类型

除了上述介绍的这些常用的类型工具,还有其它的一些类型工具,详情直接查阅官方文档:Utility Types

codes

源码

  1. /**
  2. * Make all properties in T optional
  3. */
  4. type Partial<T> = {
  5. [P in keyof T]?: T[P];
  6. };
  7. /**
  8. * Make all properties in T required
  9. */
  10. type Required<T> = {
  11. [P in keyof T]-?: T[P];
  12. };
  13. /**
  14. * Make all properties in T readonly
  15. */
  16. type Readonly<T> = {
  17. readonly [P in keyof T]: T[P];
  18. };
  19. /**
  20. * Exclude from T those types that are assignable to U
  21. */
  22. type Exclude<T, U> = T extends U ? never : T;
  23. /**
  24. * Extract from T those types that are assignable to U
  25. */
  26. type Extract<T, U> = T extends U ? T : never;
  27. /**
  28. * Exclude null and undefined from T
  29. */
  30. type NonNullable<T> = T extends null | undefined ? never : T;
  31. /**
  32. * Obtain the return type of a function type
  33. */
  34. type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
  35. /**
  36. * Obtain the return type of a constructor function type
  37. */
  38. type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;

-?表示去掉可选,变为必选。

示例

下面很多示例都来自于官方文档:Utility Types

  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. });

Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.
构造一个类型,该类型的所有属性都设置为可选。该类型工具将返回一个表示给定类型的所有子集的类型。

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

Constructs a type consisting of all properties of Type set to required. The opposite of Partial.
构造一个类型,将所有属性设置为必填,该类型由这些必填属性组成。和该类型工具功能相反的是 Partial。

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

Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.
构造一个类型,将所有属性设置为只读,该类型由这些只读属性组成,这意味着不能重新分配构造类型的属性(不能重新赋值)。

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

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.
构造一个类型,该类型中的成员存在于 UnionType 中,但不存在于 ExcludedMembers 中「1」。

4-2. 预定义的类型演算 - 图1

  1. type T = "男" | "女" | undefined | null;
  2. type NEWT = Exclude<T, null | undefined>;
  3. // => type NEWT = "男" | "女"
  1. type T0 = Extract<"a" | "b" | "c", "a" | "f">;
  2. // => type T0 = "a"
  3. type T1 = Extract<string | number | (() => void), Function>;
  4. // => type T1 = () => void

Constructs a type by extracting from Type all union members that are assignable to Union.
构造一个类型,该类型中的成员从 Type 中提取,并且它们也存在于 Union 中「2」。

4-2. 预定义的类型演算 - 图2

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

Constructs a type by excluding null and undefined from Type.
构造一个类型,该类型中不包含 null 和 undefined。

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

Constructs a type consisting of the return type of function Type.
构造一个类型,该类型由函数的返回类型构成。

  1. class C {
  2. x = 0;
  3. y = 0;
  4. }
  5. type T0 = InstanceType<typeof C>;
  6. // => type T0 = C
  7. type T1 = InstanceType<any>;
  8. // => type T1 = any
  9. type T2 = InstanceType<never>;
  10. // => type T2 = never
  11. type T3 = InstanceType<string>;
  12. // => Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.
  13. // => type T3 = any
  14. type T4 = InstanceType<Function>;
  15. // => Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'.
  16. // => Type 'Function' provides no match for the signature 'new (...args: any): any'.
  17. // => type T4 = any

Constructs a type consisting of the instance type of a constructor function in Type.
构造一个类型,该类型由类的构造器所创建的实例类型构成。

  1. class User {
  2. loginid: string
  3. }
  4. class Article {}
  5. type twoParamsConstructor = new (arg1: any, arg2: any) => User
  6. type twoParamsConstructor2 = new (arg1: any, arg2: any) => Article
  7. type Inst = InstanceType<twoParamsConstructor>;
  8. // => type Inst = User
  9. type Inst2 = InstanceType<twoParamsConstructor2>;
  10. // => type Inst2 = Article