typescript<Utility Types>内置工具 文档翻译&一眼就懂🤓傻瓜用例

141 阅读3分钟

[Utility Types - 文档链接](TypeScript: Documentation - Utility Types (typescriptlang.org))

TypeScript提供了几个实用程序类型来进行类型转换

1. Awaited

递归展开promise来获取类型

source code

  • type Awaited<T> = T extends null | undefined ? T : T extends object & {
        then(onfulfilled: infer F, ...args: infer _): any;
    } ? F extends (value: infer V, ...args: infer _) => any ? Awaited<...> : never : T
    

example

  • type A = Awaited<Promise<string>>;
    // 等同于 👇
    type A = string
    
    type B = Awaited<Promise<Promise<number>>>;
    // 等同于 👇
    type B = number
     
    type C = Awaited<boolean | Promise<number>>;
    // 等同于 👇
    type C = number | boolean
    

2. Partial

将一个类型所有属性转换为可选 3. Required 的反义

source code

  • type Partial<T> = { [P in keyof T]?: T[P] | undefined; }
    

example

  • interface IUser {
      name: string
      age: number
      department: string
    }
    type optional = Partial<IUser>
    // 等同于 👇
    type optional = {
        name?: string | undefined;
        age?: number | undefined;
        department?: string | undefined;
    }
    

3. Required

将一个类型所有属性转换为必选 2. Partial 的反义

source code

  • type Required<T> = { [P in keyof T]-?: T[P]; }
    

example

  • interface Props {
      a?: number;
      b?: string;
    }
     
    const obj: Props = { a: 5 };
    ❌ const obj1: Required<Props> = { a: 5 };
    // 报错 => Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.
    

4. Readonly

将一个类型所有属性转换为只读

source code

  • type Readonly<T> = { readonly [P in keyof T]: T[P]; }
    

example

  • interface Todo {
      title: string;
    }
     
    const todo: Readonly<Todo> = {
      title: "Delete inactive users",
    };
     
    ❌ todo.title = "Hello";
    // 报错 => Cannot assign to 'title' because it is a read-only property.
    

5. Record<Keys, Type>

构造一个对象类型,键为参数keys,值为参数type

source code

  • type Record<K extends string | number | symbol, T> = { [P in K]: T; }
    

example

  • interface CatInfo {
      age: number;
      breed: string;
    }
    type CatName = "miffy" | "boris" | "mordred";
     
    type cats = Record<CatName, CatInfo> 
    // 等同于 👇
    type cats = {
        miffy: CatInfo;
        boris: CatInfo;
        mordred: CatInfo;
    }
    

6. Pick<Type, Keys>

选取类型中指定类型 7. Omit 的反义

source code

  • type Pick<T, K extends keyof T> = { [P in K]: T[P]; }
    

example

  • interface Todo {
      title: string;
      description: string;
      completed: boolean;
    }
     
    type TodoPreview = Pick<Todo, "title" | "completed">;
    // 等同于 👇
    type TodoPreview = {
        title: string;
        completed: boolean;
    }
    

7. Omit<Type, Keys>

去除类型中某些项 6. Pick 的反义

source code

  • type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }
    

example

  • interface Todo {
      title: string;
      description: string;
      completed: boolean;
      createdAt: number;
    }
     
    type TodoPreview = Omit<Todo, "description">;
    // 等同于 👇
    type TodoPreview = {
        title: string;
        completed: boolean;
        createdAt: number;
    }
    

8. Exclude<UnionType, ExcludedMembers>

两个联合类型取差集 9. Extract 的反义

source code

  • type Exclude<T, U> = T extends U ? never : T
    

example

  • type T0 = Exclude<"a" | "b" | "c", "a">;
    // 等同于 👇
    type T0 = "b" | "c"
    
    type Shape =
      | { kind: "circle"; radius: number }
      | { kind: "square"; x: number }
      | { kind: "triangle"; x: number; y: number };
    type T1 = Exclude<Shape, { kind: "circle" }>
    // 等同于 👇
    type T1 =
      | { kind: "square"; x: number }
      | { kind: "triangle"; x: number; y: number }
    

9. Extract<Type, Union>

两个联合类型取交集 8. Exclude 的反义

source code

  • type Extract<T, U> = T extends U ? T : never
    

example

  • type T0 = Extract<"a" | "b" | "c", "a" | "f">;
    // 等同于 👇
    type T0 = "a"
    
    type Shape =
      | { kind: "circle"; radius: number }
      | { kind: "square"; x: number }
      | { kind: "triangle"; x: number; y: number };
    type T1 = Extract<Shape, { kind: "circle" }>
    // 等同于 👇
    type T1 =
      | { kind: "circle"; radius: number }
    

9. NonNullable

排除联合类型中的nullundefined

source code

  • type NonNullable<T> = T & {}
    

example

  • type T0 = NonNullable<string | number | undefined>;
    // 等同于 👇
    type T0 = string | number
    

9. Parameters

以数组类型获取函数类型中函数参数的类型

source code

  • type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never
    

example

  • type T0 = Parameters<(a: string, b: number) => void>;
    // 等同于 👇
    type T0 = [a: string, b: number]
    

10. ConstructorParameters

以数组类型获取类中构造函数参数的类型

source code

  • type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never
    

example

  • class C {
      constructor(a: number, b: string) {}
    }
    type T0 = ConstructorParameters<typeof C>;
    // 等同于 👇
    type T0 = [a: number, b: string]
    

11. ReturnType

获取函数返回值的类型

source code

  • type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any
    

example

  • function f1() {
      return { a: 1, b: 2, c: "c3" }
    }
    
    type T0 = ReturnType<typeof f1>
    // 等同于 👇
    type T0 = { a: number; b: number; c: string }
    

12. InstanceType

获取类实例的类型

source code

  • type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any
    

example

  • class C {
      x = 0;
      y = 0;
    }
    
    type T0 = InstanceType<typeof C>;
    // 等同于 👇
    type T0 = C
    
    type T1 = InstanceType<any>;
    // 等同于 👇
    type T1 = any
    

13. ThisParameterType

获取函数类型this的类型 14. OmitThisParameter 的反义

source code

  • type ThisParameterType<T> = T extends (this: infer U, ...args: never) => any ? U : unknown
    

example

  • type T0 = { a: '123' }
    
    function f1(this: T0) {
      console.log(this);
    }
    
    type T1 = ThisParameterType<typeof f1>
    // 等同于 👇
    type T1 = { a: '123' }
    

14. OmitThisParameter

用于去除函数类型中的this类型 13. ThisParameterType 的反义

source code

  • type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T
    

example

  • function f0(this: number) {
      console.log(this);
    }
    
    type T0 = typeof f0
    // 等同于 👇
    type T0 = (this: number) => void
    
    type T1 =  OmitThisParameter<typeof f0>
    // 等同于 👇
    type T1 = () => void
    

15. ThisType

--noImplicitThis模式下生效, 为this添加类型

source code

  • interface ThisType<T>
    

example

  • const obj0 = {
      f0() {
        console.log(❌ this.a);
        // 报错 => Property 'a' does not exist on type '{ bar(): void; }'.
      }
    }
    
    const obj1: ThisType<{ a: number }> = {
      f1() {
        console.log(this.a); // ok
        console.log(❌ this.b)
      }
    }