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

如何实现支持任意泛型数量的TypeScript OneOf转联合类型

实现TypeScript的OneOf类型:将任意数量泛型参数转为联合类型

直接上解决方案,用TypeScript的可变泛型参数就能实现你要的OneOf类型:

type OneOf<...Ts extends unknown[]> = Ts[number];

使用示例

完全贴合你现有代码的写法,不用加额外的方括号:

// 先定义你需要的动作类型
interface CreateAction { type: 'create'; payload: Record<string, any> }
interface DeleteAction { type: 'delete'; id: string }

export interface IView
{
  actions: OneOf<CreateAction, DeleteAction> // 等价于 CreateAction | DeleteAction
}

不管传多少个泛型参数,它都能自动转成对应的联合类型:

// 扩展示例:四个参数的情况
interface UpdateAction { type: 'update'; id: string; payload: Record<string, any> }
interface ReadAction { type: 'read'; id: string }

type AllActions = OneOf<CreateAction, DeleteAction, UpdateAction, ReadAction>
// AllActions 等价于 CreateAction | DeleteAction | UpdateAction | ReadAction

原理说明

  • ...Ts extends unknown[] 表示这个泛型可以接收任意数量的参数,所有参数会被打包成一个元组类型Ts
  • Ts[number] 是TypeScript内置的元组转联合类型语法,访问元组所有索引对应的类型后,会自动合并成联合类型

这样就不用再做正则预处理,也不用像TupleToUnion那样额外加方括号,完全匹配Typegen生成的代码格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:32:35