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;
代码:https://stackblitz.com/edit/t…