Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jet2jet opened this issue May 23, 2024 · 2 comments

Comments

@jet2jet
Copy link

jet2jet commented May 23, 2024

πŸ”Ž 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.

@whzx5byb
Copy link

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;
}

@jet2jet
Copy link
Author

jet2jet commented May 23, 2024

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

@jet2jet jet2jet closed this as not planned Won't fix, can't repro, duplicate, stale May 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants