I had a specific function to map from an array to a single item. Now that I want to map it based on the discriminator so I am trying to implement a more generic function.
I have a function with input parameter of a union type which have a discriminator.
Another parameter is the discriminator of the union[‘type’]. Why cant typescript infer the return type based on that parameter? I struggle to find an explanation.
Is it just not possible for the typescript to infer this type or may this be just an unsupported feature?
type Bar = {
name: string
type: 'Bar'
}
type Foo = {
name: string
type: 'Foo'
}
type Item = Bar | Foo;
declare const returnI: <I extends Item>(items: Item[], type: I['type']) => I | undefined
const lala = returnI([], 'Foo') // expected to be type Foo.
// ^? const lala: Item | undefined
Typescript Playground
Used Typescript version 5.4.5
Lion is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.