Flow + Redux:redux默认操作和强类型操作

时间:2017-04-05 07:00:21

标签: reactjs redux flowtype

我正在尝试使用流不相交的联合来强类型redux操作对象,如Flow文档(https://flow.org/en/docs/frameworks/redux/)中所建议的那样,但现在遇到的问题是流抛出错误处理默认的redux操作({{ 1}},@@redux/INIT等)。

此代码的示例如下:

@@redux/PROBE_UNKNOWN_ACTION

我只能在线找到这个问题的1个问题/解决方案,它使用更复杂的流运行时来解决问题。 (https://github.com/codemix/flow-runtime/issues/80

我觉得作为将Redux与Flow集成的推荐语法,应该有一个更简单的解决方案吗?我已经尝试使函数参数// Constant action type strings export const INIT_STORIES: 'INIT_STORIES' = 'INIT_STORIES'; export const UPDATE_STORY: 'UPDATE_STORY' = 'UPDATE_STORY'; // Strongly typed action objects export type InitAction = { type: typeof INIT_STORIES, stories: Array<Story> }; export type UpdateAction = { type: typeof UPDATE_STORY, storyIndex: number, story: Story }; // Disjoint union wrapper export type ActionType = | InitAction | UpdateAction; //reducer export default function storiesReducer( stories: Array<Story> = [], action: ActionType ): Array<Story> { // Error is thrown at function invocation, prior to the first inner line of function // Uncaught TypeError: [tcomb] Invalid value {"type": "@@redux/INIT" console.log(action); ... } 的类型与具有未定义字符串类型(即action)的对象不相交联合,但是在reducer内部引发静态linting / typing的类型错误,因为它无法确定{ type: string }对象的不相交联合对象的哪个分支。

1 个答案:

答案 0 :(得分:0)

最简单的解决方案,即不导入redux的完整flow-typed包,就是向{ type: $Subtype<string> }不相交的联合类型添加一个不相交的联合ActionType,如下所示:

// Disjoint union wrapper
export type ActionType = 
| InitAction
| UpdateAction
| { type: $Subtype<string> };


//reducer
export default function storiesReducer(
  stories: Array<Story> = [],
  action: ActionType
): Array<Story> {
  console.log(action);
  ...
}

如果操作类型字符串输入错误,这不会引发相应的错误,因为它允许所有字符串类型,它将允许适当的分支识别开关/案例块内的不同对象形状。