Flow 确信以下内容是安全的:
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
进行测试。
最佳答案
我相信错误消息是说 iternext.value
可能是undefined
.
iter.next()
实际上永远不会回来undefined
或null
,所以if
测试是不必要的。当迭代器耗尽时,它将返回 {value: <return value>, done: true}
。大多数生成器没有返回值,所以它将是 {value: undefined, done: true}
,因此 Flow 说“无法对可能未定义的值调用函数”:
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再次。
关于javascript - 无法对迭代器上可能未定义的值调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840017/