Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

ts映射类型

  • 作用
    • 把一种类型,映射为一种新的类型

全部映射

  • Readonly

    • 把接口中所有属性,变为只读

      interface Obj {
          x: number;
          y: number;
          z: number
      }
      
      type ReadonlyObj = Readonly<Obj>
      
  • 实现原理 js type Readonly<T> = { readonly [P in keyof T]: T[P] } - 这里in相当于是循环了一遍对象的属性

  • Partial

    • 把接口中所有属性,变为可选

      interface Obj {
          x: number;
          y: number;
          z: number
      }
      
      type PartialObj = Partial<Obj>
      
    • 实现原理

      type Partial<T> = {
          [P in keyof T]?: T[P]
      }
      

部分映射

  • Pick

    • 从接口的所有属性中,择取部分后返回

      interface Obj {
          x: number;
          y: number;
          z: number
      }
      
      type PickObj = Pick<Obj, "x" | "y">
      
    • 实现原理

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

    • 从接口的所有属性中,剔除部分后返回

      interface Obj {
          x: number;
          y: number;
          z: number
      }
      
      type OmitObj = Omit<Obj, "y" | "z">
      
    • 实现原理

      type Omit<T, K> =
          Pick<T, Exclude<keyof T, K>>
      
      • 而Exclude的原理如下

        type Exclude<T, U> =
            T extends U ? never : T
        
        • 表示如果T是U的子类,则返回never类型,否则返回T类型
        • 当T为联合类型的时候,它会自动分发条件
      • Exclude可用于按条件剔除某个类型

        type A = 'a' | 'b' | 'c';
        type B = 'a';
        
        type C = Exclude<A, B>; // 'b' | 'c';
        
      • 反过来有个Extract,原理如下

        type Extract<T, U> =
            T extends U ? T : never;
        
        • 表示如果T是U的子类,则返回T类型,否则返回never类型