-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Local variables not narrowed in lambda function bodies #15631
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
Hi! This is intended (#8541), as (in general) there is no way to see whether the callback is invoked immediately and thus in the scope of all the if conditions that can assumed to be true, or much later, when the if conditions don't have to hold anymore. |
I forget to mention: It works if you use |
Thanks @hediet that helps. So if I understand you correctly we could realistically have a situation where the variable is reassigned before the callback executes so the type guard isn't necessarily valid at the time the callback executes. That seems fine, but then why does the compiler narrow function parameters which are also mutable? If I change my earlier example about parameters to something that does mutate the parameter like this:
Then the error comes up, which is pretty cool. If I remove the assignment to parameter, there are no errors. This seems like a decent situation. Could the kind of analysis that's being done here be applied to local variables as well? |
You don't need to wrap the assignment to
Theoretically, there is no reason why this analysis wouldn't do for variables introduced with |
@hediet thanks for the explanations. Is there any easy/convenient way to get typescript to stop complaining about this in certain cases? Something that would have 0 effect on the output code? I know I could introduce another Also while casting the variable as the type without |
No, not that I know of. Sadly, there are no type assertions in TypeScript. You always have to call a function for that or directly check for null/undefined. |
The |
@RyanCavanaugh that is awesome! Thank you! |
Hello all, love your work with the language. I suspect I may have found a bug:
Local variables that are a union type (such as
type | undefined
) at declaration aren't being narrowed in lambda functions. Parameters and local aliases of those variables are.TypeScript Version: 2.2.2 / 2.3.2 / nightly (2.4.0-dev.20170506)
Code
Expected behavior:
I expect union types to be narrowed in lambda functions defined inside of a block with a type guard.
Actual behavior:
Variables that are narrowed in the block a lambda is created are not interpreted as their narrowed type inside the body of the lambda function. The above examples also apply to union types with truthy variables like
number | string
and their appropriate type guards and to functions written asfunction(){...}
.The text was updated successfully, but these errors were encountered: