-
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 guard does not affect variable inside a function #20901
Comments
Note that it occurs with this code too:
|
I think the TypeScript compiler is using the same scope rules for lambdas and functions. This' the only logical reason I see for this. I think that have to do with A function statement should behave that way because hoisting will make it available in foo top level, not like function expression (and lamdas are always). Meanwile, though I still can't phatom why @mosho1 wrote it that way, I found that the following works great. (o => o.length)(o); |
@SalathielGenese it's a distilled demonstration of the issue, not my use-case. Your solution does not solve the problem because you are assuming the function needs to be called immediately. It may be passed to another function like Yes, this should be the case for function statements, but not for function expressions and arrow functions. |
@mosho1, I attempted to :
Another workaround could be : (o: number[]) => o.length Still another : () => (<number[]>o).length All are work around to get the job done while the issue is being fixed. |
This is working as intended. Type guards remain in effect across function boundaries only when the guarded variable(s) are considered constant. This is the case for |
I see. That makes sense, thanks! |
TypeScript Version: 2.7.0-dev.201xxxxx
Code
Expected behavior:
No compile errors.
Actual behavior:
in
() => o.length
The text was updated successfully, but these errors were encountered: