Flow 无法正确推断类型

Flow doesn't infer type correctly

我在 redux 的 Action creator 中定义了多个子类型:

动作创作者:

export type Action = { type: "SELECT", index: number } | { type: "OTHER" };

减速器:

module.exports = (state: string = "", action: Action): string => {
    switch (action.type) {
        case "SELECT":
            return action.index;
        default:
            return state;
    }
};

但是如果我在常量 const select = "SELECT" 中定义 SELECT 并在上面的代码中实现它,我会收到一条错误消息:

property `index`. Property not found in object type

注意:F8 应用程序采用流模式:

https://github.com/fbsamples/f8app/blob/master/js/actions/types.js

应该如何通过避免在操作和减速器中都使用 "SELECT" 关键字来实现它?

您通常会有另一个具有操作类型的常量,它将用于您的操作和化简器。

const SELECT = 'SELECT';

甚至更好(避免任何冲突):

const SELECT = 'redux/<module>/SELECT';

在同一个动作文件中还是在另一个文件中(这完全取决于您)。然后像 export const SELECT 一样导出,像 import { SELECT } from './constants'.

一样导入

您还应该看看 redux-ducks,您可能会感兴趣。

编辑:

他们使用bitwise OR to group all possible different action cases. That helps testing whether the code is syntactically correct with flow (by setting their dispatched actions to match type Action). See their full explanation here

但这并不能消除他们必须使用他们想要的动作类型来分派动作的事实。 login