简体   繁体   中英

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

Try this code in Flow's 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. But Flow can't infer this automatically, so it complains.

I want to say to Flow, after the forEach: please assume the max variable has now been initialized. 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.)

You can initialize max by 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 :) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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