问题 Flowtype中的ES6 Map


是什么 适当的方式 处理   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声明


2451
2017-08-20 14:03


起源



答案:


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

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

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

12
2017-08-20 14:15



添加了更新 - vkurchatkin
如果唯一的目标是永远不会有 void,那么你也可以使用 if (animals.has(cageNumber)) 哪个更具可读性(并且可能更快,因为你没有分配东西以便立即删除它们)。但我不知道如何返回正确类型的东西,即。 Animal。根据Flow你的解决方案和我的两种返回类型都是 void | Animal。这是有道理的,因为您可能不希望Flow猜测您的代码的作用,因此返回类型等于 animal的类型。如果有人有解决方案,我很感兴趣。 - Christian G.
@ChristianG。这个答案中没有分配。所有发生的事情都是对参考的赋值 animal。理论上, if (animals.has(cageNumber)) { const animal: Animal = animals.get(cageNumber); ...} 可以工作,但它需要Flow知道如何 has 和 get 有关系。这是可能的,但不太可能 Map 不经常使用。无论如何,我敢打赌,使用两者 has 和 get 比使用慢 get 然后测试,因为它需要两次访问 - 除非JIT有相应的优化(我怀疑因为 Map 不经常使用)。 - maaartinus


答案:


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

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

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

12
2017-08-20 14:15



添加了更新 - vkurchatkin
如果唯一的目标是永远不会有 void,那么你也可以使用 if (animals.has(cageNumber)) 哪个更具可读性(并且可能更快,因为你没有分配东西以便立即删除它们)。但我不知道如何返回正确类型的东西,即。 Animal。根据Flow你的解决方案和我的两种返回类型都是 void | Animal。这是有道理的,因为您可能不希望Flow猜测您的代码的作用,因此返回类型等于 animal的类型。如果有人有解决方案,我很感兴趣。 - Christian G.
@ChristianG。这个答案中没有分配。所有发生的事情都是对参考的赋值 animal。理论上, if (animals.has(cageNumber)) { const animal: Animal = animals.get(cageNumber); ...} 可以工作,但它需要Flow知道如何 has 和 get 有关系。这是可能的,但不太可能 Map 不经常使用。无论如何,我敢打赌,使用两者 has 和 get 比使用慢 get 然后测试,因为它需要两次访问 - 除非JIT有相应的优化(我怀疑因为 Map 不经常使用)。 - maaartinus