ES6 Map in Flowtype

mate64 picture mate64 · Aug 20, 2016 · Viewed 8.4k times · Source

What is the appropriate way to deal with Map objects in ?

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

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

    ...
}

Error

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

Answer

vkurchatkin picture vkurchatkin · Aug 20, 2016

Type of animals.get(cageNumber) is ?Animal, not Animal. You need to check that it's not undefined:

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

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