Flowtype中的ES6 Map

时间:2016-08-20 14:03:58

标签: javascript ecmascript-6 flowtype

中处理 Map个对象的适当方式是什么?

const animals:Map<id, Animal> = new Map();

function feedAnimal(cageNumber:number) {
    const animal:Animal = animals.get(cageNumber);

    ...
}

错误

const animal:Animal = animals.get(cageNumber);
                      ^^^^^^^^^^^^^^^^^^^^^^^^ call of method `get`

const animal:Animal = animals.get(cageNumber);
                      ^^^^^^^^^^^^^^^^^^^^^^^^ undefined. This type is incompatible with
const animal:Animal = animals.get(cageNumber);
                      ^^^^^^^ Animal

Flowtype Map declaration

1 个答案:

答案 0 :(得分:14)

animals.get(cageNumber)的类型为?Animal,而不是Animal。您需要检查它是否未定义:

function feedAnimal(cageNumber:number) {
  const animal = animals.get(cageNumber);

  if (!animal) {
    return;
  } 
  // ...
}