简体   繁体   中英

Nullity guard doesn't work for inside forEach loop

In the below code, the second guard can't assert non-nullity of ab.cv inside the forEach loop, where uncommenting a local identical guard makes it work. Why is it so?

type B = {|
    bv: B[], 
    cv: ?number
|}

let ab: B = {bv: [], cv: 1}
if (ab.cv) {          // First guard
  const a = ab.cv + 1 // Works
}
var a2;
if (ab.cv) {                                           // Second guard
  ab.bv.forEach(b => {/*if (ab.cv) */a2 = ab.cv + 1})  // Doesn't work except if uncommented
                                                       // Cannot perform arithmetic operation because null or undefined [1] is not a number.
}

Flow invalidates refinement done before forEach callback. Callback is considered a function call and any function call invalidates the refinement. More info on this in docs and faq

One way to get around this is storing checked value in local variable:

const cv = ab.cv;
var a2;

if (cv) {
  ab.bv.forEach(b => {a2 = cv + 1})
}

Try

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