2017-10-19 69 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)()'),但它在技术上是正确的。 –