typescript - 将联合类型转换为交集类型

标签 typescript

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

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

我想对 FunctionUnion 应用转换以获得 FunctionIntersection

最佳答案

你想要并集到交集? Distributive conditional typesinference 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.


让我们看看它是否有效。

首先让我用括号括起来你的 FunctionUnionFunctionIntersection因为 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/

相关文章:

reactjs - 设置 react-styleguidist、创建 React App、Typescript、Material UI 和 styled-components

javascript - TypeScript 包创建声明文件

typescript - 也是 T 类型的 Keyof

angular - 使用热和冷的 Jasmine 大理石的时间/框架问题

TypeScript - 变量在某些无法确定其类型的位置隐式具有类型 'any'

angularjs - 使用 Typescript 的 Ionic 1 应用程序中的 Cordova 插件

typescript - JSPM 和 Typescript 导入

typescript - Angular 7 - PrimeNg 确认对话框问题

通过 Vue 3 (Nuxt 3) 中的对象键进行模板循环中输入值的 TypeScript 错误

TypeScript 泛型——回调函数推断