Skip to content

Nullish coalescing assignment operator does not narrow correctly #40494

@danielrentz

Description

@danielrentz

TypeScript Version: 4.0.2

Search Terms: nullish coalescing possibly undefined

Code

let x: string | undefined;

let a: string | undefined;
a ??= "x";
a.length;

let b: string | undefined;
b ??= x;
b.length;

let c: string | undefined;
c = c ?? x ?? "x";
c.length;

let d: string | undefined;
d ??= x ?? "x";
d.length;

Expected behavior:
a.length passes, b.length fails (b undefined), c.length passes, d.length passes, because it becomes a string

Actual behavior:
d.length fails because not narrowed to string.

Playground Link: https://www.typescriptlang.org/play?#code/DYUwLgBAHgXBDOYBOBLAdgcwgHwgVzQBMQAzdEQgbgChrRIBDORVTHfI08q6hiAfn4BeCACIoomgwB0oTGAAWNOuAgAjZsnRZcBYmTQUaagcOjHZIeUtr0IAY02sdHfdxr2IIz4OimxEh6W1sp2hE7a7HpchjyEpiJQ-uKS1ITBGIo0QA

Related Issues: none found

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issueHelp WantedYou can do thisRescheduledThis issue was previously scheduled to an earlier milestone

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions