I have a Foo
type which is a union of types
eg
type Foo = string | number
And I want to receive that type and transform it in an union of arrays of the types
type TransformedFoo = ToUnionOfArray<Foo> // => string[] | number[]
Usually, you can do something like Foo[]
but it isn't what I want, because that would become (string | number)[]
.
How can I have an union and transform it into a union of arrays of the types?
You can use distributive conditional types :
type Foo = string | number;
type Arrays<T> = T extends any ? T[] : never;
type TransformedFoo = Arrays<Foo>; // string[] | number[]
When conditional types act on a generic type, they become distributive when given a union type
You can use distributive conditionals in this case:
type ToUnionOfArray<T> = T extends infer I ? I[] : never;
When T is a naked type parameter in a conditional statement the conditional applies (or distributes) over every value in the input union T.
More info on how that works here: Typescript Distributive Conditional Types
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.