记一次Typescript高级用法实现

97 阅读1分钟

自言

只要不放弃,终会有所收获。

学习记录篇,记一次高级工具实现,为了在项目中更好的运用ts。

Partial

将属性全部可选

       type Partial<T>={
           [P in keyof T]:T[P]
       } 
       interface A{
       a:number;
       b:number;
       }
       type B = Partial<A>
       // B ==> {a?:number;b?:number}

Required

属性必须存在

  type Reuqired<T> = {
      [P in keyof T]-?:T[P]
  } 
  interface A{
      a?:number;
      b?:number;
  }
  
  type B = Required<A>
  // B ==> {a:number;b:number;}

Readonly

全部为只读属性

    typeof Readonly<T> ={
    readonly [P in keyof T] :T[P]
    }
     interface A {
     a:number;
     b:number;
     }
     
     type B =Readonly<A>

    // B ==> {readonly a:number; readonly b:number;}

Record

将联合指定类型

    type Record <T extends keyof any,V> = {
    [P in  T]:V
    }
    type A=  'a'|'b';
    type B = Record<A,number>;
    // B ==> {a:number;b:number;}

Pick

取出指定属性

    // keyof any ---> number | string | Symbol
    type Pick <T,K extends keyof T> = {
        [P in K]:T[P]
    }
    interface A {
    a:number;
    b:number;
    }
    type B = Pick<A,'a'>
    // B ==> {a:number}

Exclude

排除联合类型中的值

    type Exclude <T,K> = T extends K ? never : T ; 
    type A = 'a'|'b';
    type B = Exclude<A,'a'>
    // B ==> 'b'

Omit

排除指定属性,由Pick和Exclude组合

    type Omit<T,K extends keyof any> =Pick<T,Exclude<keyof T,K>>
    interface A {
    a:number;
    b:number;
    }
    
    type B = Omit<A, 'a'>
    
    // B ==> {b:number}