为什么Flow仍然抱怨document.getElementById的空值

Ale*_*rij 1 flowtype

为什么即使使用IF检查,Flow仍然会抱怨可能为null的值

if(document && document.getElementById("myID") && document.getElementById("myID").offsetWidth){
 console.log(document.getElementById("myID").offsetWidth);
}
Run Code Online (Sandbox Code Playgroud)

给出了这个错误

   ^ property `offsetWidth`. Property cannot be accessed on possibly null value
Run Code Online (Sandbox Code Playgroud)

log*_*yth 6

Flow无法知道第一次调用成功getElementById意味着后者也会成功.尽管如此,阅读该offsetWidth属性可能会导致在下次调用时getElementById开始返回null.

您需要存储该值,例如

const myIdEl = document && document.getElementById("myID");

if(myIdEl && myIdEl.offsetWidth) {
   console.log(myIdEl.offsetWidth);
}
Run Code Online (Sandbox Code Playgroud)

这种方式在引用之后myIdEl无法变为 null.