当您从逻辑中知道类型是正确的时,如何“修复”流类型?

pau*_*l23 3 javascript flowtype option-type

考虑一个接受/创建可能类型(例如数字)的函数;然后是另一个不接受此类型的函数。为了使其“工作”,我通过在其周围添加条件来保护不采用 Maybe-type 的函数。

一个简单的例子:

/* @flow */

export function nullOrUndefined(val: mixed): boolean {
    return val === null || val === undefined;
}

function foo(x: ?number) {
  console.log(!nullOrUndefined(x) ? addOne(x) : null);
}


function addOne(x: number) {
  return x + 1;
}
Run Code Online (Sandbox Code Playgroud)

nullOrUndefined将是一个通用的防护,我创建它是为了具有一个具有表现力的简单实用函数,因此我不必不断地在线输入“复杂”测试。

上面的功能可以工作,并且不会抛出错误。(只要foo接收到一个数字,未定义或空。

但是流程给出以下错误:

8:   console.log(!nullOrUndefined(x) ? addOne(x) : null);
                                              ^ Cannot call `addOne` with `x` bound to `x` because null or undefined [1] is incompatible with number [2].
    References:
    7: function foo(x: ?number) {
                       ^ [1]
    12: function addOne(x: number) {
                           ^ [2] 
Run Code Online (Sandbox Code Playgroud)

一个小测试

我理解为什么会发生此错误(流程无法查看任何任意函数,甚至nullOrUndefined不会位于同一文件中。

但是,我该如何解决这个问题呢?以外// $FlowFixMe?或者在这种情况下,明确的“忽略行”是正确的用法?

Lyl*_*ood 5

啊,Flow 为您的案例提供一流的支持。您的错误可以通过添加一个令牌来解决:%checks

export function nullOrUndefined(val: mixed): boolean %checks {
  ...
Run Code Online (Sandbox Code Playgroud)

(尝试链接)

%checks用于向流程指示所指示的函数是类型细化谓词。请注意,流程的细化是非常基本的,并且很容易被基本上比您的函数更复杂的函数混淆。

  • 虽然这应该可行,但在跨文件使用“类型细化谓词”时(使用 es6 导入系统),这实际上会失败。 (4认同)