Home > OS >  In TypeScript, how to convert all types within a Union to an array of that type
In TypeScript, how to convert all types within a Union to an array of that type

Time:07-08

Let's say I have the following:

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[];

CodePudding user response:

You can use a distributive conditional type (a conditional type of the form T extends X ? Y : Z where T is a generic type parameter) to split a union into its members, perform a transformation on each member, and combine the result into another 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

  • Related