0

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"
redsun
  • 3
  • 1
  • 2
    `Union` - is unordered set of data. There is no `first` and `last` element in the union. - Furthermore, there is no such guarantee. See my [question](https://stackoverflow.com/questions/63662061/why-element-order-in-union-type-has-changed) and github [issue#17944](https://github.com/microsoft/TypeScript/issues/17944) – captain-yossarian from Ukraine Sep 29 '22 at 13:37
  • 1
    You shouldn't try to do this unless it's just for fun. There is no guarantee of ordering. – jcalz Sep 29 '22 at 14:08

1 Answers1

0

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

nullptr
  • 3,701
  • 2
  • 16
  • 40
  • 1
    Obligatory link to answer with jcalz's comments about unions to tuples: https://stackoverflow.com/a/55128956/18244921 – kelsny Sep 29 '22 at 13:48
  • 2
    You should definitely discourage this sort of thing, since it is [unbelievably fragile](https://tsplay.dev/wQxgJW) – jcalz Sep 29 '22 at 14:08