Is there any way Typescript can infer b to also be of type U extends Foo ? string : number? If a is of type U extends Foo ? string : number then in the true branch adding a number to string would result in string. In the false branch, adding a number to number would end up being a number. Thus I'd expect the type of b to also be inferred to U extends Foo ? string : number. Or is it a wrong assumption?
When I run the snippet below I get the following error:
Operator '+' cannot be applied to types 'U extends Foo ? string : number' and 'number'.(2365)
interface Foo {
propA: boolean;
propB: boolean;
}
declare function f<T>(x: T): T extends Foo ? string : number;
function foo<U>(x: U, d: number) {
const a = f(x);
const b = a + 2;
}
function add(s: string | number) { return s + 1; } // Error- Roberto Zvjerkovićais of a conditional type, not a union type - Lukasz Prus