2017-10-19 71 views
-1

流納以下是安全的:功能無法在迭代器可能未定義的值被稱爲

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

回答

1

我相信錯誤信息是說iternext.value可能是undefined

iter.next()實際上從未返回undefinednull,所以if測試是不必要的。當迭代器耗盡時,它將返回{value: <return value>, done: true}。大多數發電機沒有返回值的,所以這將是{value: undefined, done: true},因此流式細胞說「功能不能在可能未定義的值被稱爲」:

const m = new Map([['foo', 'bar']]); 
 
const iter = m.keys(); 
 
console.log(iter.next()); 
 
console.log(iter.next()); 
 
console.log(iter.next());

調用iternext.value()因爲你有一個字符串映射,所以肯定是錯的。如果你有一個函數映射(並且迭代器沒有耗盡),你只能調用它。

你可能想再次看看iterator protocol

0

我被Flow錯誤消息誤導了。將value()更改爲value將導致無流量錯誤。不過,我不確定我是否理解錯誤信息或Flow認爲正在發生的事情。措辭似乎暗示可能未定義的值是iternext,這是沒有意義的。

公平地流高亮文本確實似乎表明該問題不是狹隘與iternext

enter image description here

+1

當你'foo.bar()',那麼首先'值foo.bar'被檢索,然後調用該值。因爲'foo.bar'可以是'undefined',所以你會看到這個消息。更簡單的例子:'var foo = undefined; FOO();'。如果'iternext'是'undefined',那麼錯誤信息就會像*「Property無法訪問可能未定義的值」*。我同意這聽起來很奇怪,當你第一次閱讀它(我相信這是因爲我們「看到」foo.bar()更像是'foo。(bar())'而不是'(foo.bar)()'),但它在技術上是正確的。 –