Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract specific union item given generic param in typescript

Given an union of typescript objects, I want to extract a specific union item.
This will help me to dynamically type a function where a specific id is passed as params.

typescript playground

Here is an example of what I want to achieve:


type A = {
  id: 'a',
  search: {
    a: number
  }
}

type B = {
  id: 'b',
  search: {
    b: string
  }
}

type MyUnion = A | B

type GetFromUnion<T extends MyUnion['id']> = // complete the implementation

/**
 * I expect type C to be equal to:
 * 
 * type C = {
 *   id: 'b',
 *   search: {
 *    b: string
 *   }
 * }
 */
type C = GetFromUnion<'b'>

What I tried, but doesn't work:

// Always return never
type GetFromUnion<T extends MyUnion['id']> = MyUnion['id'] extends T ? MyUnion : never
like image 497
Simon Bruneaud Avatar asked Nov 24 '25 10:11

Simon Bruneaud


1 Answers

Extract to the rescue:

type GetFromUnion<T extends MyUnion['id']> = Extract<MyUnion, {id : T}>

The implementation of Extract is:

type Extract<T, U> = T extends U ? T : never;
like image 138
spender Avatar answered Nov 27 '25 00:11

spender



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!