1

I have a construct like this:

interface Foo<T> {
    value: T;
}

interface Bar<T> {
    value: T;
}

function transform<T>(foos: Foo<T>[]): Bar<T> {
    // ...
}

I want to call transform() like this: transform([{ value: 'a' }, { value: 1 }]) and have that result in the type Bar<string | number>. However, what actually happens in the code above is that the inferred type is string and calling transform() with the second array element results in an error because value is a number and not a string. Is it possible to change this code to make it correctly infer the type string | number?

Lehks
  • 2,582
  • 4
  • 19
  • 50
  • I would say you will have to use multiple signature overloads to do that just like eg RxJs has – Antoniossss Jun 24 '23 at 17:04
  • 1
    TS doesn't like to synthesize unions from multiple inference candidates. Instead you can make the generic type an array instead of the element, as shown [in this playground link](https://tsplay.dev/m075GN). Does that fully address the question? If so I'll write up an answer (or find an appropriate dupe source). If not, what am I missing? – jcalz Jun 24 '23 at 17:09
  • @jcalz This works perfectly, thanks. I had not thought of using `keyof T` like that. – Lehks Jun 24 '23 at 17:17

0 Answers0