当你从逻辑上知道类型是正确的时候,如何"fix"流类型?

How to "fix" flow types when you know from the logic that the type is correct?

考虑一个 takes/creates 可能类型(例如数字)的函数;然后是另一个不采用 this maybe 类型的函数。为了做到这一点 "work" 我通过在其周围添加条件来保护不采用可能类型的函数。

一个简单的例子:

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

nullOrUndefined 将是一个通用的守卫,我创建它是为了具有一个简单的实用函数,它具有表现力,因此我不必不断地在行中键入 "complex" 测试。

以上功能会起作用,并且不会抛出错误。 (只要 foo 收到一个数字,未定义或 null。

但是流程给出了以下错误:

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] 

A small test

我明白为什么会出现这个错误(流程无法查看任何任意函数,并且 nullOrUndefined 甚至不会 成为 在同一个文件中。

但是,我该如何解决这个问题?除了 // $FlowFixMe 以外?或者在这种情况下显式 "ignore line" 是正确的用法吗?

啊,flow 对您的案例有第一个 class 支持。您的错误可以通过添加一个标记来解决:%checks.

export function nullOrUndefined(val: mixed): boolean %checks {
  ...

(try link)

%checks用于指示流指示的函数是type refinement predicate。请注意,流程中的细化是非常基本的,很容易被基本上比你的复杂的函数混淆。