้•œๅƒ็ซ™็‚น ยท ๆœฌ้กต็”ฑ็ฌฌไธ‰ๆ–น GitHub ๅช่ฏป้•œๅƒๆไพ›๏ผŒ้ž GitHub ๅฎ˜ๆ–น็ซ™็‚น๏ผŒไธๆŽฅๅ—ไปปไฝ•็™ปๅฝ•ๆˆ–ๅ‡ญๆฎ่พ“ๅ…ฅใ€‚ๅ‰ๅพ€ github.com
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.

Activity

  1. whzx5byb commented on May 23, 2024

    @whzx5byb

    Per #44730:

    Narrowing through indirect references occurs only when the conditional expression or discriminant property access is declared in a const variable declaration with no type annotation, and the reference being narrowed is a const variable, a readonly property, or a parameter for which there are no assignments in the function body.

    So just mark the property a as readonly and it works.

    interface Foo {
        readonly a: string | null;
    }
  2. jet2jet commented on May 23, 2024

    @jet2jet
    Author

    Thanks for the response. I missed that this is applied only for 'a readonly property'.
    I'll close the issue.

  3. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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