简体   繁体   English

如果Flow无法自动推断var,那么如何声明该变量已被初始化?

[英]How to declare that a var has now been initialized, if Flow can't infer it automatically?

Try this code in Flow's REPL : 在Flow的REPL中尝试以下代码

const numbers = [5, 3, 22, 2, 6];

let max: number;

numbers.forEach(item => {
  if (!max || item > max) max = item;
});

console.log(max++); // type error

I can be certain that max will have been initialized as a number before the max++ expression. 我可以确定max将被初始化为max++表达式之前的数字。 But Flow can't infer this automatically, so it complains. 但是Flow无法自动推断出这一点,因此它会抱怨。

I want to say to Flow, after the forEach: please assume the max variable has now been initialized. 我要对Flow说,在forEach之后:请假设max变量现在已经初始化。 Is there a way to do this? 有没有办法做到这一点?

(Related – Flow has 'declarations': declare var max: number; – this lets you declare that a number variable called var exists in global scope. But you can't use it to redeclare something already declared in your own scope.) (相关– Flow具有“声明”: declare var max: number; –这使您可以声明全局范围内存在一个名为var的数字变量。但是您不能使用它来重新声明已经在自己的范围内声明的内容。)

You can initialize max by let max: number = numbers[0]; 您可以通过let max: number = numbers[0];初始化max let max: number = numbers[0]; . That should stop flow from complaining. 那应该阻止人们抱怨。

You can also rewrite your code in a less mutable way: 您还可以用一种不太易变的方式重写代码:

const numbers = [5, 3, 22, 2, 6];

const max = numbers.reduce((max, item) => item > max ? item : max,
  Number.NEGATIVE_INFINITY);

console.log(max + 1);

This avoids any kind of mutation, making the life easier for Flow (and probably for humans too :) ) 这样可以避免任何形式的变异,从而使Flow的生活更加轻松(也可能对人类来说也很容易:))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM