-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Nullish coalescing assignment operator does not narrow correctly #40494
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
Comments
I'd like to take a look into this bug :) |
Btw, same problem arises with the |
Seems caused by control flow bind. Current flow is
The |
I independently ran into this bug and confirmed that my reduced test case fails in 4.1.4 but passes with the playground for #40536: let a: number | undefined
let b: number | undefined
// TS fails to infer that `a` must be `number`, so `a + 1` errors with:
// Object is possibly 'undefined'. (2532)
a ??= b ?? 1
console.log(a + 1)
// Should be equivalent but without the assignment to `a`, but this works.
console.log((a ?? b ?? 1) + 1) Is there any reason that fix can't be merged yet? |
I think this should be reopened (or I could create a new issue, let me know). Take the following code snippet, where there is a bug ( let elem!: Element;
let selector1 =
(elem.hasAttribute('name') && `[name='${elem.getAttribute('name')!}']`)
?? elem.tagName;
const s1: string = selector1; // Correctly reports that false is not assignable to string
let selector2;
selector2 = elem.hasAttribute('name') && `[name='${elem.getAttribute('name')!}']`;
selector2 ??= elem.tagName;
const s2: string = selector2; // No error as selector2 has been incorrectly narrowed to string, where there should be!! It seems as though Or is this #40359? |
Sounds a bit more like #40359. You might try to narrow down which version of typescript first exhibited the failure, if it's a regression. |
TypeScript Version: 4.0.2
Search Terms: nullish coalescing possibly undefined
Code
Expected behavior:
a.length
passes,b.length
fails (b
undefined),c.length
passes,d.length
passes, because it becomes a stringActual behavior:
d.length
fails because not narrowed tostring
.Playground Link: https://www.typescriptlang.org/play?#code/DYUwLgBAHgXBDOYBOBLAdgcwgHwgVzQBMQAzdEQgbgChrRIBDORVTHfI08q6hiAfn4BeCACIoomgwB0oTGAAWNOuAgAjZsnRZcBYmTQUaagcOjHZIeUtr0IAY02sdHfdxr2IIz4OimxEh6W1sp2hE7a7HpchjyEpiJQ-uKS1ITBGIo0QA
Related Issues: none found
The text was updated successfully, but these errors were encountered: