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>
>;
差集
type Diff<T extends object, U extends object> = Omit<
T & U,
keyof Intersection<T, U>
>;
將指定屬性變為Optional
type PartialKey<U extends object, k extends keyof U> = Partial<U> & Omit<U, k>;
將指定屬性變為Required
type RequiredKey<U extends object, K extends keyof U> = U &
Required<Pick<U, K>>;
獲取陣列元素型別
type ArrayItem<T extends unknown[]> = T extends (infer P)[] ? P : never;
獲取Record中value型別
type RecordValueType<U extends Record<any, unknown>> = U extends Record<any, infer P> ? P : never;
獲取Promise返回型別
type PromiseReturnType<U extends Promise<unknown>> = U extends Promise<infer P> ? P : never;