简体   繁体   English

FlowType:null检查失败

[英]FlowType: null check fails

Why does the null-check fail in func1 while it is ok in func2 为什么func1中的null检查失败,而在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 实例

I don't know the reasons why Flow doesn't support this, but it doesn't. 我不知道Flow不支持这个的原因,但事实并非如此。 It currently requires that checks for type refinements actually happen in the if statement, and does not track them if they are abstracted out into a separate variable. 它目前要求对类型细化的检查实际上发生在if语句中,如果它们被抽象为单独的变量,则不会跟踪它们。

There is an alternative that may be acceptable to you (I'm not sure it's documented anywhere): 有一种替代方案可供您接受(我不确定它是否记录在任何地方):

/* @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 %checks return type indicates to Flow that it should look into the body of the function to figure out what it implies about the types of the variables it is passed. 特殊的%checks返回类型向Flow指示它应该查看函数体,以弄清楚它传递的变量类型意味着什么。 I believe there are some restrictions on what can be in the body of such a function. 我相信对这种功能的身体有什么限制。 It may even be the case that it just has to return a single expression. 甚至可能只需返回单个表达式。 This should give you enough to experiment with it, though. 但是,这应该足以让你尝试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM