流纳以下是安全的:功能无法在迭代器可能未定义的值被称为
const a: ?any = {};
if (a!=null) {
console.log(a.toString());
}
…但以下引发错误:
const m: Map<string, string> = new Map();
const iter = m.keys();
const iternext = iter.next();
if (iternext!=null) {
const ignore = iternext.value(); // Flow doesn't like this
}
错误是:
call of method `value`. Function cannot be called on possibly undefined value
这是为什么? 经测试最新的0.57.3
。
当你'foo.bar()',那么首先'值foo.bar'被检索,然后调用该值。因为'foo.bar'可以是'undefined',所以你会看到这个消息。更简单的例子:'var foo = undefined; FOO();'。如果'iternext'是'undefined',那么错误信息就会像*“Property无法访问可能未定义的值”*。我同意这听起来很奇怪,当你第一次阅读它(我相信这是因为我们“看到”foo.bar()更像是'foo。(bar())'而不是'(foo.bar)()'),但它在技术上是正确的。 –