将ES6 Map与Flow类型一起使用

Asa*_*atz 4 dictionary flowtype es6-map

我正在努力绕过流程,我努力使其与ES6兼容 Map

考虑以下简单情况(现场演示):

// create a new map
const m = new Map();

m.set('value', 5);

console.log(m.get('value') * 5)
Run Code Online (Sandbox Code Playgroud)

流抛出:

console.log(m.get('value') * 5)
               ^ Cannot perform arithmetic operation because undefined [1] is not a number.
References:
[LIB] static/v0.72.0/flowlib/core.js:532:     get(key: K): V | void;
                                                               ^ [1]
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

const m:Map<string, number> = new Map();

m.set('value', 5);

console.log(m.get('value') * 5)
Run Code Online (Sandbox Code Playgroud)

但是我遇到了同样的错误

我相信这是因为flow认为值也可以是数字以外的其他值,因此我尝试使用严格的setter和getter(live demo)包装地图:

type MyMapType = {
    set: (key: string, value: number) => MyMapType,
    get: (key: string) => number
};

function MyMap() : MyMapType {
    const map = new Map();

    return {
        set (key: string, value: number) {
          map.set(key, value);
          return this;
        },
        get (key: string) {
          return map.get(key);
        }
    }
}


const m = MyMap();

m.set('value', 5);

const n = m.get('value');

console.log(n * 2);
Run Code Online (Sandbox Code Playgroud)

但是我得到了:

get (key: string) {
^ Cannot return object literal because undefined [1] is incompatible 
with number [2] in the return value of property `get`.
References:
[LIB] static/v0.72.0/flowlib/core.js:532:     get(key: K): V | void;
                                                               ^ [1]
get: (key: string) => number                            ^ [2]
Run Code Online (Sandbox Code Playgroud)

我怎么能告诉流程我只处理数字地图?

编辑:

Typescript方法对我来说更有意义,它抛出set而不是get

// TypeScript

const m:Map<string, number> = new Map();

m.set('value', 'no-number'); // << throws on set, not on get

console.log(m.get('value') * 2);
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使Flow行为相同?

Jam*_*aus 5

Flow试图告诉您的是,通过调用map.get(key).get(...)可能(V)或可能不void从该映射返回某些内容。如果在地图中找不到该键,则对的调用.get(...)将返回undefined。要解决此问题,您需要处理未定义返回的情况。这是几种方法:

尝试

const m = new Map();

m.set('value', 5);

// Throw if a value is not found
const getOrThrow = (map, key) => {
  const val = map.get(key)
  if (val == null) {
    throw new Error("Uh-oh, key not found") 
  }
  return val
}

// Return a default value if the key is not found
const getOrDefault = (map, key, defaultValue) => {
  const val = map.get(key)
  return val == null ? defaultValue : val
}

console.log(getOrThrow(m, 'value') * 5)
console.log(getOrDefault(m, 'value', 1) * 5)
Run Code Online (Sandbox Code Playgroud)

映射的map.get(key)键入原因可能不包含该键的值。如果键上没有值,则将引发运行时错误。Flow开发人员决定,他们宁愿强迫开发人员(您和我)在我们编写代码时考虑问题,然后在运行时查找问题。V | void