假设我有以下内容:
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
形式的条件类型,其中 T
是 generic 类型参数)来分割 union进入其成员,对每个成员执行转换,并将结果组合到另一个联合中:
type DistribArrayify<T> = T extends unknown ? Array<T> : never;
type UnionType = CustomType1 | CustomType2 | CustomType3;
type UnionTypeArr = DistribArrayify<UnionType>;
// type UnionTypeArr = CustomType1[] | CustomType2[] | CustomType3[]
关于typescript - 在 TypeScript 中,如何将 Union 内的所有类型转换为该类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72905570/