Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Map in Flowtype

What is the appropriate way to deal with ecmascript-6 Map objects in flowtype?

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

like image 790
mate64 Avatar asked Aug 20 '16 14:08

mate64


1 Answers

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;
  } 
  // ...
}
like image 98
vkurchatkin Avatar answered Oct 05 '22 17:10

vkurchatkin