mat*_*e64 16 javascript ecmascript-6 flowtype
在flowtype中处理ecmascript-6对象的适当方法是什么? Map
const animals:Map<id, Animal> = new Map();
function feedAnimal(cageNumber:number) {
const animal:Animal = animals.get(cageNumber);
...
}
Run Code Online (Sandbox Code Playgroud)
错误
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
Run Code Online (Sandbox Code Playgroud)
vku*_*kin 14
类型animals.get(cageNumber)是?Animal,不是Animal.您需要检查它是否未定义:
function feedAnimal(cageNumber:number) {
const animal = animals.get(cageNumber);
if (!animal) {
return;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)