有没有办法将联合类型转换为交集类型:
type FunctionUnion = (() => void) | ((p: string) => void)
type FunctionIntersection = (() => void) & ((p: string) => void)
我想对 FunctionUnion
应用转换以获得 FunctionIntersection
最佳答案
你想要并集到交集? Distributive conditional types和 inference from conditional types可以做到这一点。 (虽然不要认为可以进行交集到并集,抱歉)这是邪恶的魔法:
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
那个分配工会U
并将其重新打包成一个新的联合,其中所有成分都处于逆变位置。这允许将类型推断为交集 I
,如手册中所述:
Likewise, multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred.
让我们看看它是否有效。
首先让我用括号括起来你的 FunctionUnion
和 FunctionIntersection
因为 TypeScript 似乎比函数返回更紧密地绑定(bind)并集/交集:
type FunctionUnion = (() => void) | ((p: string) => void);
type FunctionIntersection = (() => void) & ((p: string) => void);
测试:
type SynthesizedFunctionIntersection = UnionToIntersection<FunctionUnion>
// inspects as
// type SynthesizedFunctionIntersection = (() => void) & ((p: string) => void)
看起来不错!
注意一般UnionToIntersection<>
公开了 TypeScript 认为是实际联合的一些细节。例如,boolean
显然在内部表示为 true | false
, 所以
type Weird = UnionToIntersection<string | number | boolean>
成为
type Weird = string & number & true & false
在 TS3.6+ 中急切地减少到
type Weird = never
因为不可能有一个 string
的值和 number
和 true
和 false
.
关于typescript - 将联合类型转换为交集类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50374908/