-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
type narrowing for instance fields should be discarded after await #31429
Comments
Duplicate of #27900 |
Duplicate #9998 |
I'll close this duplicate but I guess I'll elaborate that my particular use case is for a class that acts as an asynchronous background processor. So, while it's performing some tasks, certain state might change from under its feet. For example, at the beginning of a task, the "state" could be "RUNNING". And, in the middle, the user could ask the processor to stop. So, the "state" becomes "STOPPING". In its loop, the processor checks the "state" to see if it is still "RUNNING", and continues if it is. However, the flow analysis says it is always "RUNNING", which isn't true, in this case. |
In spite of #9998 (while I generally agree with the conclusions there) I think it might be worth consideration, at least, that Almost by definition, a function resuming from an We already reset narrowings inside of function expressions, which manifests today for |
This is hard for me to agree with, especially with the increasing prevalence of async functions and calls. For example: async function fn(obj: { fileName?: string }) {
if (obj.fileName !== undefined) {
const contents = await fs.readFile(obj.fileName);
console.log(obj.fileName.length); // Error...?
}
}
The closer analog to |
Good point re: prevalence of async calls, although there is still some nondeterminism introduced by the event loop (you don’t know how many or even which other event handlers will fire before your function gets to resume executing) that simply isn’t a factor with synchronous calls—though I suppose
This I wasn’t aware of, thanks—I had thought narrowings were always reset at function boundaries and wasn’t aware of this exception. That said, |
TypeScript Version: 3.4.1, 3.3.0
Search Terms: type narrow, instance field, discard, await
Code
Expected behavior:
Comparison to
false
should work.Type of
this.b
should beboolean
.Actual behavior:
Comparison to
false
does not work.Type of
this.b
istrue
.This example is contrived but my actual use case is with
enum
type comparisons.I know the enum value can possibly change after the
await
but TS doesn't know that.Workaround:
Use a type assertion,
Playground Link: Here
The text was updated successfully, but these errors were encountered: