Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Turn Union Into a Tuple In TypeScript? [duplicate]

Given a type 'a' | 'b' | 'c', if and how is it possible to generate the type ['a', 'b', 'c']?

like image 451
Mateja Petrovic Avatar asked Oct 16 '25 03:10

Mateja Petrovic


1 Answers

UnionToTuple convert every union to tuple.
In your case UnionToTuple<'a' | 'b' | 'c'> will create ['a', 'b', 'c'] type

// UnionToIntersection<A | B> = A & B
type UnionToIntersection<U> = (
  U extends unknown ? (arg: U) => 0 : never
) extends (arg: infer I) => 0
  ? I
  : never;

// LastInUnion<A | B> = B
type LastInUnion<U> = UnionToIntersection<
  U extends unknown ? (x: U) => 0 : never
> extends (x: infer L) => 0
  ? L
  : never;

// UnionToTuple<A, B> = [A, B]
type UnionToTuple<T, Last = LastInUnion<T>> = [T] extends [never]
  ? []
  : [Last,...UnionToTuple<Exclude<T, Last>>]

Typescript playground

P.S.: Found this and many useful typescript generic types in Typescript challanges

like image 152
Mike Kokadii Avatar answered Oct 18 '25 01:10

Mike Kokadii