Nullish coalescing operator does not understand cases where at least one operand is guaranteed to not be null, but not which one is not null #61670
Labels
Duplicate
An existing issue was already created
🔎 Search Terms
"nullish coalescing" "narrowing" "type narrowing" "if statement" "or expression"
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code: https://www.typescriptlang.org/play/?target=6&ts=5.9.0-dev.20250507#code/MYewdgzgLgBAhgLhmArgWwEYFMBOMA+yKANsTALwwAM8E8YAngNwBQoksGSqmuBRpCtVr1mLAJYAzGAAo4MAITlKqQfkIZFygcQCUMAN4sAkO2gxg3dNjyV5AfnswMrAL4sgA
💻 Code
🙁 Actual behavior
The type checker generates an error when assigning to
c
: Type 'number | null' is not assignable to type 'number'.Type 'null' is not assignable to type 'number'.
This is incorrect because the
if
statement guarantees that at least one ofa
orb
is not null.This also happens with code that excludes rather than narrows, e.g.:
🙂 Expected behavior
No error should occur because the
if
statement guarantees that at least one ofa
orb
is not null. If the code was modified so that an explicit type was not specified,c
should be inferred asnumber
.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: