Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distribute a generic type over a union

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)

like image 573
Thomas Aribart Avatar asked Sep 19 '25 17:09

Thomas Aribart


1 Answers

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

like image 145
leetwinski Avatar answered Sep 21 '25 06:09

leetwinski