流无法识别回调中的优化 [英] Flow doesn't recognise refinement inside callback

查看:51
本文介绍了流无法识别回调中的优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码通过了流检查:

/* @flow */

function test (list: ?Array<string>): Promise<number> {
  if(list !== null && list !== undefined) {
    return Promise.resolve(list.length)
  } else {
    return Promise.resolve(0)
  }
}

console.log(test(null))

以下内容出现空检查错误

Whereas the following gets a null check error

/* @flow */

function test (list: ?Array<string>): Promise<number> {
  if(list !== null && list !== undefined) {
    return Promise.resolve().then(() => list.length)
  } else {
    return Promise.resolve(0)
  }
}

console.log(test(null))

错误:

property `length`. Property cannot be accessed on possibly null value

清楚的列表不能是null,因此必须有一些有关代码结构的内容,以使流程无法识别这一点.

Clearly list cannot be null so there must be something about the code structure that makes flow unable to recognise this.

我想了解我遇到的限制以及如何解决它.谢谢!

I would like to understand what limitation I am hitting and how I can work around it. Thanks!

推荐答案

基本上,Flow不知道执行() => list.length时将保留类型细化(空检查).在该回调内部,Flow仅查看列表的类型–列表可以为空.

Basically, Flow doesn't know that your type refinement (null check) will hold at the time when () => list.length is executed. Inside that callback Flow only looks at the type of list – which says it can be null.

第一个和第二个片段之间的区别在于,第二个片段中的list越过了函数边界–您在与精炼其类型不同的函数中使用了它.

The difference between first and second snippet is that in the second snippet list is crossing a function boundary – you're using it in a different function than where you refined its type.

一种解决方案是将list.length提取到一个变量中,然后在回调中使用该变量.

One solution is to extract list.length into a variable, and use that variable in the callback.

var length = list.length;
return Promise.resolve().then(() => length)

这也可能起作用:

var list2: Array<string> = list;
return Promise.resolve().then(() => list2.length)

请注意,即使是立即调用的回调,例如,使用mapforEach时. Flow的github上有一个与此有关的问题,但是在快速搜索后我找不到它.

Note that this problem exists even for immediately invoked callbacks, e.g. when using map or forEach. There is an issue on flow's github about this, but I couldn't find it after a quick search.

这篇关于流无法识别回调中的优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆