【问题标题】:Strange type empty Flow syntax inside default statement of Redux reducerRedux reducer默认语句中的奇怪类型空流语法
【发布时间】:2017-12-16 21:55:25
【问题描述】:

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

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

它看起来像没有返回值类型但带有奇怪类型“空”的参数的不合适的函数类型语句,我找不到关于它的文档。

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

【问题讨论】:

    标签: redux flowtype


    【解决方案1】:

    empty 是 Fl​​ow 的 bottom type。我相信它最初引入的主要动机是对称性,但事实证明它有一些用途。正如您已经确定的那样,在这种情况下可以使用它来使 Flow 强制穷举。它可以类似地用于if/else 语句链中。

    但是,当您希望 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);
    

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

    【讨论】:

    • 对空的很好的解释,谢谢,有没有网址可以让我了解更多信息?另外,很高兴了解有关 (action: empty); 语法的更多信息。 - 它不是返回类型,也不是函数参数类型。 babel 会以某种方式转换它吗?
    • 如果它记录在某处,我不知道。这个语法只是一个类型断言。您可以在左侧放置任何表达式,在右侧放置任何类型。
    • AFAIK 这是为没有键的对象定义类型的唯一方法。 type emptyObj = { [string]: empty }
    猜你喜欢
    • 2020-04-13
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2017-08-20
    • 2013-07-13
    相关资源
    最近更新 更多