流程:使用地图时出错
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
的调用可能 return void
正如您在 V | void
.
中看到的那样
Flow 无法知道您的密钥是否已定义,因为这可能会在运行时发生变化。
因此,在访问 push
方法之前,您需要检查 returned 值是否不是 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);
我刚开始在我的一个项目中使用 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
的调用可能 return void
正如您在 V | void
.
Flow 无法知道您的密钥是否已定义,因为这可能会在运行时发生变化。
因此,在访问 push
方法之前,您需要检查 returned 值是否不是 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);