在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
答案 0 :(得分:14)
animals.get(cageNumber)
的类型为?Animal
,而不是Animal
。您需要检查它是否未定义:
function feedAnimal(cageNumber:number) {
const animal = animals.get(cageNumber);
if (!animal) {
return;
}
// ...
}