You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
closure.ts(13,5): error TS2531: Object is possibly 'null'.
If I remove the forEach loop and just write a.method(), it compiles. Also, if I remove the line a = a || new A(), it compiles. Both things together seem to confuse TypeScript.
If I remove the if (!a) { return; } it fails with the same error, which seems like a bug as well.
I understand how this closures in general could be difficult to reason about, but in this case, I think TypeScript should be able to figure it out, since the closure function cannot be called until after the if (!a) { return; }, after which point a is never assigned.
The text was updated successfully, but these errors were encountered:
TypeScript resets the narrowed type when a reference is used inside a closure. This is done because the reference may be of different type if the closure is asynchronously executed (i.e. subsequent code may change the type). As TypeScript does not have a mechanism to tell whether a function is immediately invoked or not, it applies the following two rules:
if the variable is declared as const, it preserves its narrowed type (as const variables cannot be reassigned)
if a variable or parameter is not reassigned in function's body it's treated as if it was const
So to fix your issue either assign the new value to const a2 or omit the assignment as it seems redundant.
TypeScript Version: 2.0.3 (also the 2.1 RC)
Code
With --strictNullChecks,
Expected behavior:
I expect this to compile
Actual behavior:
I get an error,
closure.ts(13,5): error TS2531: Object is possibly 'null'.
If I remove the forEach loop and just write
a.method()
, it compiles. Also, if I remove the linea = a || new A()
, it compiles. Both things together seem to confuse TypeScript.If I remove the
if (!a) { return; }
it fails with the same error, which seems like a bug as well.I understand how this closures in general could be difficult to reason about, but in this case, I think TypeScript should be able to figure it out, since the closure function cannot be called until after the
if (!a) { return; }
, after which pointa
is never assigned.The text was updated successfully, but these errors were encountered: