Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting first type from union typescript

Tags:

typescript

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"
like image 717
redsun Avatar asked Oct 27 '25 05:10

redsun


1 Answers

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]

playground

like image 126
nullptr Avatar answered Oct 29 '25 22:10

nullptr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!