【问题标题】:Nullity guard doesn't work for inside forEach loop无效保护不适用于内部 forEach 循环
【发布时间】:2020-12-15 12:52:27
【问题描述】:

在下面的代码中,第二个守卫不能在forEach 循环内断言ab.cv 的非空性,其中取消注释本地相同的守卫使其工作。为什么会这样?

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.
}

【问题讨论】:

    标签: javascript functional-programming flowtype


    【解决方案1】:

    流程使forEach 回调之前完成的优化无效。回调被认为是一个函数调用,任何函数调用都会使细化无效。 docsfaq 中的更多信息

    解决此问题的一种方法是将检查值存储在局部变量中:

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

    Try

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      相关资源
      最近更新 更多