流納以下是安全的:功能無法在迭代器可能未定義的值被稱爲
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)()'),但它在技術上是正確的。 –