You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Invalid type inference for optional chaining operator when nullish check is extracted to const varaiableΒ #58632
interfaceFoo{a: string|null;}functionbar(foo: Foo|null){constisNullish=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.
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.
Activity
whzx5byb commentedon May 23, 2024
Per #44730:
So just mark the property
aas readonly and it works.jet2jet commentedon May 23, 2024
Thanks for the response. I missed that this is applied only for 'a readonly property'.
I'll close the issue.