[英]How to declare that a var has now been initialized, if Flow can't infer it automatically?
在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
我可以确定max
将被初始化为max++
表达式之前的数字。 但是Flow无法自动推断出这一点,因此它会抱怨。
我要对Flow说,在forEach之后:请假设max
变量现在已经初始化。 有没有办法做到这一点?
(相关– Flow具有“声明”: declare var max: number;
–这使您可以声明全局范围内存在一个名为var
的数字变量。但是您不能使用它来重新声明已经在自己的范围内声明的内容。)
您可以通过let max: number = numbers[0];
初始化max let max: number = numbers[0];
。 那应该阻止人们抱怨。
您还可以用一种不太易变的方式重写代码:
const numbers = [5, 3, 22, 2, 6];
const max = numbers.reduce((max, item) => item > max ? item : max,
Number.NEGATIVE_INFINITY);
console.log(max + 1);
这样可以避免任何形式的变异,从而使Flow的生活更加轻松(也可能对人类来说也很容易:))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.