Skip to content

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

@RubyTunaley

Description

@RubyTunaley

🔎 Search Terms

"nullish coalescing" "narrowing" "type narrowing" "if statement" "or expression"

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about nullish coalescing and type narrowing.

⏯ Playground Link

Playground link with relevant code: https://www.typescriptlang.org/play/?target=6&ts=5.9.0-dev.20250507#code/MYewdgzgLgBAhgLhmArgWwEYFMBOMA+yKANsTALwwAM8E8YAngNwBQoksGSqmuBRpCtVr1mLAJYAzGAAo4MAITlKqQfkIZFygcQCUMAN4sAkO2gxg3dNjyV5AfnswMrAL4sgA

💻 Code

const a: number | null = 0 as any;
const b: number | null = 0 as any;
if (a !== null || b !== null) {
	const c: number = a ?? b;
}

🙁 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 of a or b is not null.

This also happens with code that excludes rather than narrows, e.g.:

const a: number | null = 0 as any;
const b: number | null = 0 as any;
if (a === null && b === null) {
	throw new Error();
}
const c: number = a ?? b;

🙂 Expected behavior

No error should occur because the if statement guarantees that at least one of a or b is not null. If the code was modified so that an explicit type was not specified, c should be inferred as number.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions