Simon Bruneaud
Simon Bruneaud

Reputation: 2557

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

Upvotes: 3

Views: 109

Answers (1)

spender
spender

Reputation: 120420

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;

Upvotes: 3

Related Questions