你想要并集到交集吗?分配条件类型 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
.