Closed as not planned
Description
Suggestion
Conditional + nullish coalescing doesn't seem to reify the type correctly.
π Search Terms
nullish coalescing
nullish coalescing conditional
#43705 sounds maybe related but hard to tell (examples listed don't seem the same)
β Viability Checklist
- [Y] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [Y] This wouldn't change the runtime behavior of existing JavaScript code
- [Y] This could be implemented without emitting different JS based on the types of the expressions
- [Y] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [Y] This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Conditional type narrowing through the ||
operator + the use of the nullish coalescing operator should understand each other to reify the type correctly.
π Motivating Example
declare function foo(): string | undefined
const a = foo()
const b = foo()
if (a != undefined || b != undefined) {
const c = a ?? b
}
c
should have type string
but instead it has type string | undefined
because TS hasn't reasoned that the only way into the block is if a ?? b
must be non-null.
π» Use Cases
Came up in my code where I had two strings and each could be string | undefined
and I wanted to nullish coalesce but only if one of them was not undefined. Had to use !
as a workaround