简体   繁体   中英

Property nullity check doesn't work on iteration

In the code below, the ab.bv check doesn't work to iterate over ab.bv . It works, however, to access elements of ab.bv . Has the if (ab.bv) check not checked for nullity of ab.bv ?

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

const c: B => void = n => {}

let ab: B = {bv: []}
if (ab.bv) {
  for (const v2 in ab.bv) { // Error in ab.bv: cannot iterate using a `for...in` statement because array type [1] is not an object, null, or undefined. [invalid-in-rhs]
    c({...ab})
  }
  c({...ab.bv[0]}) // Works
}

The refinement works, just the error is a bit not clear. Flow is trying to tell you that you should use for...of to iterate the array instead of for...in (as you'll get the indexes instead of array items):

let ab: B = {bv: []}
if (ab.bv) {
  for (const v2 of ab.bv) { // Works
    c(v2)
  }
  c({...ab.bv[0]}) // Works
}

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