分享幾個我工作中封裝的typeScript方法

阿古達木發表於2021-10-20

TS目前支援的方法已經有不少了https://www.typescriptlang.or...
但是還是不夠,下面分享幾個我自己封裝的常用方法


交集

type Intersection<T extends object, U extends object> = Pick<
  T,
  Extract<keyof T, keyof U> & Extract<keyof U, keyof T>
>;

image.png


差集

type Diff<T extends object, U extends object> = Omit<
  T & U,
  keyof Intersection<T, U>
>;

image.png


將指定屬性變為Optional

type PartialKey<U extends object, k extends keyof U> = Partial<U> & Omit<U, k>;

image.png


將指定屬性變為Required

type RequiredKey<U extends object, K extends keyof U> = U &
  Required<Pick<U, K>>;

image.png


獲取陣列元素型別

type ArrayItem<T extends unknown[]> = T extends (infer P)[] ? P : never;

image.png


獲取Record中value型別

type RecordValueType<U extends Record<any, unknown>> = U extends Record<any, infer P> ? P : never;

image.png


獲取Promise返回型別

type PromiseReturnType<U extends Promise<unknown>> = U extends Promise<infer P> ? P : never;

image.png

程式碼: https://stackblitz.com/edit/t...

相關文章