Skip to content

Invalid type inference for optional chaining operator when nullish check is extracted to const varaiable #58632

Description

🔎 Search Terms

"optional chaining operator", null check

🕗 Version & Regression Information

  • This is the behavior in every version I tried (from 4.4.4 to 5.5.0-dev.20240523)

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.5.0-dev.20240523#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChkHJwBcyAzmFKAObIA+yIArgDYsDcuAvrjEyAjDB0IZACM4UABQxMpDFgbM2AShz5CCERWTAyAOVYs9AC2QBeZLPQB+AHRwLl5Rw0FgMZFL2G2ptXiEQchQEGBMUCCcQTxBAPRxIRAADuhQYMgARADyYgBWEIK6ZMipZGTAYiwAnsgA5C51dlIATACsAMwAjCqZVmlZ1g6ZbshaIGToLBB2LOjUMpgOdmDoAKrJydAAwnBkEFIqKpw8QA

💻 Code

interface Foo {
    a: string | null;
}
function bar(foo: Foo | null) {
    const isNullish = foo?.a == null;
    if (isNullish) {
        return;
    }
    // report "Object is possibly 'null'.(2531)" for "foo.a"
    console.log(foo.a.toUpperCase());
}

🙁 Actual behavior

Report an error Object is possibly 'null'.(2531) for foo.a

🙂 Expected behavior

No error is reported

Additional information about the issue

I don't know this behavior is a bug or intended, but based on PR #44730 , I chose 'bug' for this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions