Zarch
Zarch

Reputation: 123

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

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

Upvotes: 2

Views: 96

Answers (1)

jcalz
jcalz

Reputation: 328262

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

Upvotes: 2

Related Questions