将联合类型转换为相交类型

Titian Cernicova-Dragomir:

有没有一种方法可以将联合类型转换为交叉类型:

type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void

我想申请一个转型FunctionUnion来获得FunctionIntersection

jcalz:

您想要工会相交吗?分布式条件类型条件类型的推断可以做到这一点。(抱歉,不要认为有可能进行交叉到工会)这是邪恶的魔咒:

type UnionToIntersection<U> = 
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never

这将联合分发U并重新包装成新的联合,其中所有要素都处于对立位置。I如手册中所述,这允许将类型推断为交集

同样地,在反变量位置上针对同一类型变量的多个候选会导致推断相交类型。


让我们看看它是否有效。

首先让我FunctionUnion加上您的括号FunctionIntersection因为TypeScript似乎比函数返回更紧密地绑定并集/交集:

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 and number true and 的值false

希望能有所帮助。祝好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章