ES6在Flowtype中映射

ES6 Map in Flowtype

本文关键字:映射 Flowtype ES6      更新时间:2023-09-26

什么是合适的方式处理流类型中的ecmascript-6 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声明

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

function feedAnimal(cageNumber:number) {
  const animal = animals.get(cageNumber);
  if (!animal) {
    return;
  } 
  // ...
}