将并集类型转换为交集类型

2023-12-07

有没有办法将联合类型转换为交集类型:

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

我想应用一个转换FunctionUnion to get FunctionIntersection


你想要并集到交集吗?分配条件类型 and 从条件类型推断可以做到这一点。 (不过,抱歉,我认为不可能进行交集到并集)这是邪恶的魔法:

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

分配工会U并将其重新包装成一个新的联盟,其中所有成员都处于相反的位置。这允许将类型推断为交集I,正如手册中提到的:

同样,逆变位置中同一类型变量的多个候选者会导致推断出交集类型。


让我们看看它是否有效。

首先让我把你的FunctionUnion and FunctionIntersection因为 TypeScript 似乎比函数返回更紧密地绑定并集/交集:

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

Testing:

type SynthesizedFunctionIntersection = UnionToIntersection<FunctionUnion>
// inspects as 
// type SynthesizedFunctionIntersection = (() => void) & ((p: string) => void)

看起来不错!

请注意,一般情况下UnionToIntersection<>公开了 TypeScript 认为的实际联合的一些细节。例如,boolean显然内部表示为true | false, so

type Weird = UnionToIntersection<string | number | boolean>

becomes

type Weird = string & number & true & false

在 TS3.6+ 中,它被急切地简化为

type Weird = never

因为不可能有一个值string and number and true and false.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将并集类型转换为交集类型 的相关文章

随机推荐