Given a type 'a' | 'b' | 'c'
, if and how is it possible to generate the type ['a', 'b', 'c']
?
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
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