1
头图

TS currently supports a lot of https://www.typescriptlang.org/docs/handbook/utility-types.html
But it's still not enough. Let me share a few common methods of my own packaging.


intersection

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

image.png


difference set

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

image.png


the specified attribute to Optional

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

image.png


changes the specified attribute to Required

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

image.png


Get the array element type

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

image.png


Get the value type in the Record

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

image.png


Get Promise return type

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

image.png

Code: https://stackblitz.com/edit/typescript-ug3pat?file=index.ts


阿古达木
574 声望17 粉丝

牛逼的工程师就是能用简单的代码和思路写出复杂的功能