Closed as not planned
Closed as not planned
Description
Suggestion
π Search Terms
type inference in repeated expression
repeated or condition
or condition
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
This code (playground link):
function required(x: number): number {
return x;
}
function optional(a?: number, b?: number): number {
if (a || b) {
return required(a || b);
}
return 0;
}
produces this type error on the return required(a || b)
line:
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
but TypeScript should be able to infer that a || b
can only be a number
not number | undefined
because the ||
expression must be true in the if
block.
π Motivating Example
I am checking two optional properties of an object and using them interchangeably. Currently I have to use an as
expression.
π» Use Cases
See above.