Flowtype中的ES6 Map

mat*_*e64 16 javascript ecmascript-6 flowtype

处理对象的适当方法是什么? 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)

Flowtype Map声明

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)