Suppose I have a type
:
type T1 = "Hello" | "World"
I would like to extract the first type
from the union
, without knowing what that type
is. I would like a type
of the form:
type T2 = "Hello"
Suppose I have a type
:
type T1 = "Hello" | "World"
I would like to extract the first type
from the union
, without knowing what that type
is. I would like a type
of the form:
type T2 = "Hello"
As multiple people have already mentioned, you should probably not do this in production code.
You can use the code from this answer with one small change:
type UnionToParm<U> = U extends any ? (k: U) => void : never;
type UnionToSect<U> = UnionToParm<U> extends ((k: infer I) => void) ? I : never;
type ExtractParm<F> = F extends { (a: infer A): void } ? A : never;
type SpliceOne<Union> = Exclude<Union, ExtractOne<Union>>;
type ExtractOne<Union> = ExtractParm<UnionToSect<UnionToParm<Union>>>;
type ToTuple<Union> = ToTupleRec<Union, []>;
type ToTupleRec<Union, Rslt extends any[]> =
SpliceOne<Union> extends never ? [ExtractOne<Union>, ...Rslt]
: ToTupleRec<SpliceOne<Union>, [ExtractOne<Union>, ...Rslt]>
;
type test = ToTuple<5 | 6 | "l">;
type firstOfUnion = test[0]
You can get the nth type from the union by using test[n]