Redux reducer的默认语句中的奇怪类型空流语法

eug*_*ekr 3 flowtype redux

我在这里搜索与redux一起使用flow的方法时找到了代码示例:https://flow.org/en/docs/frameworks/redux/

特殊的语法是(action:empty); 它只是一些流魔法,只是在switch语句的默认情况下使用,还是有其他用途?

它看起来像没有返回值类型的不合适的函数类型语句但是带有奇怪类型'empty'的参数,我找不到文档.

// @flow
type State = { +value: boolean };

type FooAction = { type: "FOO", foo: boolean };
type BarAction = { type: "BAR", bar: boolean };

type Action = FooAction | BarAction;

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "FOO": return { ...state, value: action.foo };
    case "BAR": return { ...state, value: action.bar };
    default:
      (action: empty);
      return state;
  }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ote 6

empty是Flow的底部类型.我认为其最初引入的主要动机是对称性,但事实证明它具有一些用途.正如您所知,在这种情况下可以使用它来使Flow强制执行详尽无遗.它可以在if/ elsestatements语句链中类似地使用.

但是,当您希望Flow阻止任何实际值在某处结束时,它可以随时使用.这很模糊,所以这里有几个例子:

// Error: empty is incompatble with implicitly-returned undefined
function foo(): empty {
}

// No error since the function return is not reached
function foo2(): empty {
  throw new Error('');
}

function bar(x: empty): void {
}

// Error: too few arguments
bar();
// Error: undefined is incompatible with empty
bar(undefined);
Run Code Online (Sandbox Code Playgroud)

foo示例中,我们可以看到Flow强制return在返回的函数中永远不会达到a empty.在该bar示例中,我们可以看到Flow阻止调用该函数.