typescript - 在 TypeScript 中,如何将 Union 内的所有类型转换为该类型的数组

标签 typescript union-types

假设我有以下内容:

type UnionType = CustomType1 | CustomType2 | CustomType3;

// is there a way to accomplish this, without having to type it out like so.
type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[];

最佳答案

您可以使用 distributive conditional type (T extends X ? Y : Z 形式的条件类型,其中 Tgeneric 类型参数)来分割 union进入其成员,对每个成员执行转换,并将结果组合到另一个联合中:

type DistribArrayify<T> = T extends unknown ? Array<T> : never;

type UnionType = CustomType1 | CustomType2 | CustomType3;

type UnionTypeArr = DistribArrayify<UnionType>;
// type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[]

Playground link to code

关于typescript - 在 TypeScript 中,如何将 Union 内的所有类型转换为该类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72905570/

相关文章:

javascript - TypeScript 如何推断 `this` 的类型?

reactjs - react-redux : "super calls are not permitted outside constructors or in nested functions inside constructors" 中的 typescript 错误

arrays - typescript :如何将键数组转换为联合类型的对象?

reactjs - typescript - 如何结合联合和交集类型

node.js - "SyntaxError: Cannot use import statement outside a module"依赖项

javascript - HttpInterceptor 在拦截器内调用另一个服务并等待响应

javascript - 如何将 JS 字符串数组转换为与 io-ts 的联合?

typescript - 在 TypeScript 中,为什么异步函数不能返回 T | 类型的联合 promise <T>?

typescript - 为什么 TypeScript 会忽略类型约束?

ios - SwiftUI 我自己的渲染函数的返回类型是什么?