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
letdata: {[k: string]: string}={}functiondeleteOnClick(){letkey=findKey()if(!key){return;}letkey2=keywindow.addEventListener("click",()=>{deletedata[key2]// this is okdeletedata[key]// type error, key can be null})}functionfindKey(): string|null{returnnull}
Expected behavior: delete data[key] contains no error Actual behavior: delete data[key] contains type error
This is a design limitation. When a local variable is declared with let or var the control flow analyzer assumes that there could be subsequent assignments to the variable following the creation of a closure that references the variable, and therefore that narrowed types may no longer be correct (it's just that there aren't any such assignments in your example). Your example works if you use const in the declaration of key because it is then known that there won't be any further assignments and that it is safe to carry the narrowed types into the closure.
We could theoretically do more work in the control flow analyzer to determine that there are no assignments to a particular variable following the creation of a function closure that references the variable, but it's not trivial.
Activity
hgl commentedon May 24, 2020
Asked on SO, doesn't get any response. Looks like a bug to me.
MartinJohns commentedon May 24, 2020
Duplicate of #9998.
hgl commentedon May 24, 2020
Thanks
hgl commentedon May 24, 2020
On second thought this doesn’t seem to be a duplicate. key is locally defined, there is no way the addEventListener call can reset it back to null.
Not sure it’s flow control related.
ahejlsberg commentedon May 25, 2020
This is a design limitation. When a local variable is declared with
letorvarthe control flow analyzer assumes that there could be subsequent assignments to the variable following the creation of a closure that references the variable, and therefore that narrowed types may no longer be correct (it's just that there aren't any such assignments in your example). Your example works if you useconstin the declaration ofkeybecause it is then known that there won't be any further assignments and that it is safe to carry the narrowed types into the closure.We could theoretically do more work in the control flow analyzer to determine that there are no assignments to a particular variable following the creation of a function closure that references the variable, but it's not trivial.