Is there a way in TS to "distribute" a generic type over a union?
type Container<A> = { value: A };
type Containers<string | number> = Container<string> | Container<number>
(Assuming that we know from the context when to apply Containers
vs Container
)
surprisingly, type inference would do that for you:
type Container<T> = { value: T }
type Containers<T> = T extends infer A ? Container<A> : never;
the compiler is smart enough to disjoint all of them:
type C = Containers<string | number | {x: number} | {z: string} | boolean>
type C
expands the following way:
type C = Container<string> |
Container<number> |
Container<false> |
Container<true> |
Container<{
x: number;
}> |
Container<{
z: string;
}>
ts-playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With