最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6 Map in Flowtype - Stack Overflow

programmeradmin3浏览0评论

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 inpatible with
const animal:Animal = animals.get(cageNumber);
                      ^^^^^^^ Animal

Flowtype Map declaration

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 inpatible with
const animal:Animal = animals.get(cageNumber);
                      ^^^^^^^ Animal

Flowtype Map declaration

Share Improve this question edited Aug 20, 2016 at 14:11 mate64 asked Aug 20, 2016 at 14:03 mate64mate64 10.1k17 gold badges65 silver badges98 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

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;
  } 
  // ...
}
发布评论

评论列表(0)

  1. 暂无评论