Reputation: 2557
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.
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