[英]Flow: Getting error when using Map
我刚刚开始在我的一个项目中使用Facebook Flow实现类型检查,并且遇到了一些问题。 我正在尝试对地图执行以下操作:
/* @flow */
let testMap: Map<string, Array<number>> = new Map();
let key: string = "testString";
if (!testMap.has(key)) {
testMap.set(key, [])
}
testMap.get(key).push(1);
但我收到一个错误消息:
Cannot call `testMap.get(...).push` because property `push` is missing in undefined [1]
这当然是因为Map接口中的get函数定义为:
get(key: K): V | void;
但是我期望Flow能够意识到该键实际上是在上方设置的。
关于如何更改代码以使Flow满意的任何建议?
非常感谢你!
如您所提到的,这里的问题是您对Map.get
的调用可能返回void
就像在V | void
看到的那样V | void
V | void
。
Flow没有机会知道您的密钥是否已定义,因为在运行时可能会更改。
因此,您需要在访问返回值的push
方法之前检查返回的值是否undefined
。
const arr = testMap.get(key);
if (arr) {
arr.push(1)
} else {
// map "testMap" didn't contain a value for key "key"
}
另一种方法是这样的:
let arr = testMap.get(key);
if (!arr) {
arr = [];
testMap.set(key, arr);
}
arr.push(1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.