【问题标题】:FlowType: null check failsFlowType:空检查失败
【发布时间】:2017-07-31 20:31:53
【问题描述】:

为什么在func1 中空检查失败,而在func2 中正常

/* @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));
  }
}

Live example

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    我不知道 Flow 不支持此功能的原因,但它不支持。它目前要求在 if 语句中实际检查类型细化,并且如果它们被抽象为单独的变量,则不会跟踪它们。

    您可能会接受另一种选择(我不确定它是否记录在任何地方):

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

    (tryflow)

    特殊的%checks 返回类型向Flow 表明它应该查看函数体,以找出它对传递的变量类型的含义。我相信这样一个函数的主体中可以包含一些限制。甚至可能只需要返回一个表达式。不过,这应该足以让您进行试验。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多