FlowType: null error checked

Why func1 null-check error fail with func1 while it is in func2 state

 /* @flow */ const func1 = (arr?: Array<*>) => { const isArrayNotEmpty = arr && arr.length; if (isArrayNotEmpty) { arr.forEach((element) => console.log(element)); } } const func2 = (arr?: Array<*>) => { if (arr && arr.length) { arr.forEach((element) => console.log(element)); } } 

Living example

+5
source share
1 answer

I do not know the reasons why Flow does not support this, but it is not. Currently, this requires that type checking checks are actually performed in the if and do not track them if they abstract from a single variable.

There is an alternative that may be acceptable to you (I'm not sure if it is documented):

 /* @flow */ const func1 = (arr?: Array<*>) => { if (isArrayNotEmpty(arr)) { arr.forEach((element) => console.log(element)); } } function isArrayNotEmpty(x: mixed): %checks { return x && x.length; } 

( tryflow )

The special type of return %checks tells Flow that it should look into the body of the function to find out what it means with respect to the types of variables passed in. I believe that there are some restrictions on what may be in the body of such a function. Perhaps it’s just that you just need to return one expression. That should give you enough to experiment with it.

+3
source

Source: https://habr.com/ru/post/1265292/


All Articles