You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何将联合类型所有成员转换为对应类型数组

实现方案

利用 TypeScript 的分布式条件类型特性即可实现需求,无需手动枚举联合类型的每个成员。
分布式条件类型的核心规则:当条件类型的判断参数是裸类型参数(即没有被元组、数组等外层结构包裹的泛型参数),且传入值为联合类型时,TypeScript 会自动遍历联合的每一个成员,单独代入条件逻辑计算,最后把所有计算结果重新组合为新的联合类型。

具体代码

首先定义通用的数组转换工具类型:

type ToArray<T> = T extends any ? T[] : never;

直接传入原联合类型即可得到目标类型,和手动逐一枚举成员写出来的UnionTypeArr类型完全等价:

type UnionType = CustomType1 | CustomType2 | CustomType3;
// 计算结果等价于 CustomType1[] | CustomType2[] | CustomType3[]
type UnionTypeArr = ToArray<UnionType>;

注意:不要直接写type UnionTypeArr = UnionType[],这个类型代表「数组成员可以是三种类型任意混合的数组」,和需求要求的「数组成员全为同一种类型的数组的联合」语义完全不同。

原理说明

  • 当传入CustomType1 | CustomType2 | CustomType3这个联合类型时,ToArray<UnionType>会被TypeScript自动拆解为三个分支计算:
    (CustomType1 extends any ? CustomType1[] : never)
    | (CustomType2 extends any ? CustomType2[] : never)
    | (CustomType3 extends any ? CustomType3[] : never)
    
    最终合并得到的结果就是我们需要的数组成员类型统一的数组联合。
  • 写法中的T extends any是触发分布式逻辑的常用写法,替换为T extends unknown效果完全一致。
  • 该写法具备自动同步能力:后续如果UnionType新增、删除成员类型,UnionTypeArr会自动同步更新,不需要手动维护映射关系。

内容的提问来源于stack exchange,提问作者Zarch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 21:27:25