redux reducer flow不推断类型

时间:2017-05-29 20:25:56

标签: ecmascript-6 redux flowtype

我在flow docs基本上执行基本的redux-reducer示例时遇到了流错误。

此处添加到代码中的流出错:在REMOVE开关案例上:action未解析为正确的类型。

如果我将鼠标悬停在vscode中的payload上,则会在ADD情况下将其显示为AddAction,但在REMOVE情况下,它会显示为所有行动,即Action

我缺少什么或理解错误? Flow应该从Actions联合中删除正确的类型到ifswitch内唯一可能的类型。

// @flow
const initialState = [];

type Item = { id: number, data: string };
type State = Item[];

type AddAction = {
  type: 'ADD',
  payload: Item
};

type RemoveAction = {
  type: 'REMOVE',
  payload: { id: number }
};

type ClearAction = {
  type: 'CLEAR'
};

type Action = AddAction | RemoveAction | ClearAction;

const reducer: (State, Action) => State = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD': {
      return [...state, action.payload];
    }

    case 'REMOVE': {
      return state.filter(t => t.id !== action.payload.id);
                                               ^ property `payload`. Property not found in
    }

    case 'CLEAR': {
      return [];
    }

    default:
      (action: empty);
      return state;
  }
};

export default reducer;

1 个答案:

答案 0 :(得分:3)

好的,似乎问题是在action箭头函数中使用Array.filter

如果我用

替换REMOVE案例内容
case 'REMOVE': {
  const id = action.payload.id;
  return state.filter(t => t.id !== id);
}

错误消失了。

我猜流量无法推断出箭头函数内的类型。知道原因会很有趣。

编辑:related question

因此,flow使联合细化无效,因为它假定filter()可能对reducer参数actiondocs)产生副作用。在使用之前将操作或有效负载存储在const中。修复此问题。

相关问题