[英]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.