-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Closed
Closed
Copy link
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issueRecent RegressionThis is a new regression just found in the last major/minor version of TypeScript.This is a new regression just found in the last major/minor version of TypeScript.
Milestone
Description
π Search Terms
narrowing, strict equals, property access, boolean false, undefined
π Version & Regression Information
- This changed between versions 5.2 and 5.3
- This also happens in the nightly
β― Playground Link
π» Code
interface Foo {
bar: boolean
}
const getFoo = (): Foo | undefined => {
return Math.random() > 0.5 ? { bar: false } : undefined
}
const foo = getFoo()
if (foo?.bar === false) {
console.log(foo)
}
// @ts-expect-error - foo is possibly undefined
console.log(foo.bar)π Actual behavior
In line 13 and following, foo is incorrectly narrowed to just Foo (whereas it was previously Foo | undefined), although we learned nothing about it from the preceding if as that did not influence control flow.
Unused '@ts-expect-error' directive.(2578)
π Expected behavior
TS should report an error when accessing foo.bar as foo can potentially be undefined.
Additional information about the issue
I originally discovered this issue in JSX with a snippet similar to:
function Component () {
const foo = getFoo()
return (
<div>
{foo?.bar === false && 'foo'}
{foo.bar ? 'true' : 'false'}
</div>
)
}There as well, the access foo.bar is allowed due to the preceding check, although they are completely separate.
Note that changing it to === true or removing the checks entirely fixes the problem.
quezak, 403-html, MichalJasiorowski, beardedramp, lukaszjaskowski and 10 more
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issueRecent RegressionThis is a new regression just found in the last major/minor version of TypeScript.This is a new regression just found in the last major/minor version of TypeScript.