实现一个 UnionToIntersection 工具类型,用于把联合类型转换为交叉类型。具体的使用示例如下所示:
type UnionToIntersection<U> = // 你的实现代码
// 测试用例
type U0 = UnionToIntersection<string | number> // never
type U1 = UnionToIntersection<{ name: string } | { age: number }> // { name: string; } & { age: number; }
解法:
type ToUnionFunction<U> = U extends any ? (x: U) => any : never
type UnionToIntersection<U> = ToUnionFunction<U> extends (x: infer P) => any
? P
: never
1、联合类型分配律 2、逆变、协变