如何实现支持任意泛型数量的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[]表示这个泛型可以接收任意数量的参数,所有参数会被打包成一个元组类型TsTs[number]是TypeScript内置的元组转联合类型语法,访问元组所有索引对应的类型后,会自动合并成联合类型
这样就不用再做正则预处理,也不用像TupleToUnion那样额外加方括号,完全匹配Typegen生成的代码格式。
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

