简体   繁体   中英

Flow: Getting error when using Map

I have just started to implement type checking using Facebook Flow in one of my projects, and have encountered some issues. I am trying to do the following with a Map:

/* @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);

But I am getting an error saying:

Cannot call `testMap.get(...).push` because property `push` is missing in undefined [1]

Se example in try flow: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVMCmAXM3MDO2AsgIYAOAXGGeQDxEBOAlgHYDmANGAIKOOkAnnVYBXALYAjTIwB8ssAF4wrTEloAKAJQBuDDjABrTIOpM27JWABE+IgGVsLDtb2pmUMBoCEdkhQA6AAtSAg1jQS0tMABvVDA8Qn9yAIIccJNuAG0AXS1UAF90P1oA9nSIrQDyUQIgjQBGXVQgA

This is of course because the get function in the Map interface is defined as:

get(key: K): V | void;

But I was expecting Flow to recognize that the key is actually being set just above.

Any suggestions on how I should change my code in order to make Flow happy?

Thank you very much!

As you mentioned, the problem here is that your call to Map.get may return void as you can see in V | void V | void .

Flow has no chance to know whether your key was defined or not as this may change during runtime.

Thus you need to check whether the returned value is not undefined before accessing it's push method.

const arr = testMap.get(key);

if (arr) {
  arr.push(1)
} else {
  // map "testMap" didn't contain a value for key "key"
}

full demo in flow repl: https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVMCmAXM3MDO2AsgIYAOAXGGeQDxEBOAlgHYDmANGAIKOOkAnnVYBXALYAjTIwB8ssAF4wrTEloAKAJQBuDDjABrTIOpM27JWABE+IgGVsLDtb2pmUMBoCEdkhQA6AAtSAg1jQS0tMABvVDA8Qn9yAIIccJNuAG0AXS1UAF90AGM4ViIwUn4rP1oA9nSI3XQPLyrGaLiE9oDyUQIgjQBGfIKwTBg02PiwYGAwcQobWoprMAATZnXWAHJcUtZsUjZKsAA3UhhRTDAoOEYjExsI60KgA


Another approach would be like this:

let arr = testMap.get(key);

if (!arr) {
  arr = [];
  testMap.set(key, arr);
}

arr.push(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM