首页 文章

Flow Redux:使用redux默认操作和强类型操作时出错

提问于
浏览
0

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

此代码的示例如下:

// 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);
  ...
}

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

我觉得作为将Redux与Flow集成的推荐语法,应该有一个更简单的解决方案吗?我已经尝试将函数参数 action 的类型与具有未定义字符串类型的对象(即 { type: string } )进行不相交联合,但是在reducer内部引发了静态linting / typing的类型错误,因为它无法确定不相交的哪个分支union对象 action 对象是 .

1 回答

  • 0

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

    // 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);
      ...
    }
    

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

相关问题