0

我有一个小问题,正在输入我的 Redux Reducer。我知道这个问题,已经得到了普遍的回答,但我发现缺乏解决方案,我会称它们为比其他任何东西更多的解决方法。

问题: 我有一个 Redux Reducer。在其中,有 3 个函数管理状态 和LoadingSuccessFailure提供必要的状态dataerrors状态。现在TS进入游戏。基本上我得到这个错误:

TS2418: Type of computed property's value is
'(state: ImmutableObjectMixin<IState>, { error }: ActionFailure<Type.LIST_ITEMS_FAILURE, HttpError>) => ImmutableObjectMixin<...>',
which is not assignable to type '(state: ImmutableObjectMixin<IState>, action: ActionWithPayload<Type.LIST_ITEMS_SUCCESS, IItems[]>, { error }: ActionFailure<Type.LIST_ITEMS_FAILURE, HttpError>) => ImmutableObjectMixin<...>'.

Types of parameters '__1' and 'action' are incompatible.
Property 'error' is missing in type 'ActionWithPayload<Type.ITEMS_SUCCESS, IItems[]>' but required in type 'ActionFailure<Type.LIST_ITEMS_FAILURE, HttpError>'.

错误出现在以下块中:

const ACTION_HANDLERS: {
  [key: string]: (
    state: ImmutableObjectMixin<IState>,
    action: ActionWithPayload<Type.LIST_ITEMS_SUCCESS, IItems[]>,
    { error }: ActionFailure<Type.LIST_ITEMS_FAILURE, HttpError>
  ) => ImmutableObjectMixin<IState>;
} = {
  [Type.LIST_ITEMS_ATTEMPT]: onListFetching,
  [Type.LIST_ITEMS_SUCCESS]: onListFetchingSuccess,
  [Type.LIST_ITEMS_FAILURE]: onListFetchingFailure // This line throws the TS Error
};

现在,我error在相关答案中阅读了有关为所有可能的属性提供 , 或将它们全部设为可选的信息,但它们并没有真正解决我的问题。

以下是功能:

const onListFetching = (state: ImmutableObjectMixin<IState>): ImmutableObjectMixin<IState> =>
  state.merge({
    listFetching: true,
    list: [],
    errorListing: null
  });

const onListFetchingSuccess = (
  state: ImmutableObjectMixin<IState>,
  action: ActionWithPayload<Type.LIST_ITEMS_SUCCESS, IItems[]>
): ImmutableObjectMixin<IState> => {
  const { payload = [] } = action;
  return state.merge({
    listFetching: false,
    list: payload,
    errorListing: null
  });
};

const onListFetchingFailure = (
  state: ImmutableObjectMixin<IState>,
  { error }: ActionFailure<Type.LIST_ITEMS_FAILURE, HttpError>
): ImmutableObjectMixin<IState> =>
  state.merge({
    listFetching: false,
    errorListing: error,
    list: []
  });

键入此内容的任何帮助将不胜感激。我觉得问题,可能就在key属性上。由于我们正在重组error,但我可能是错的。谢谢..

4

1 回答 1

0

我没有自己输入,而是使用了 Handlers Generic 接口,来自redux-sauce.

这是界面本身:

  export interface Handlers<S> {
    [type: string]: (state: S, action: Action) => S;
  }

它基本上与我的打字完全相同,但它与 TS 错误重叠。不过不知道为什么。如果你有答案,这将是有用的。

这是新的代码:

const ACTION_HANDLERS:Handlers<ImmutableObjectMixin<IState>> = {
  [Type.LIST_ITEMS_ATTEMPT]: onListFetching,
  [Type.LIST_ITEMS_SUCCESS]: onListFetchingSuccess,
  [Type.LIST_ITEMS_FAILURE]: onListFetchingFailure
};

一切都像一个字符,。但如果它可以进一步改进,请告诉我..

于 2020-01-14T23:04:07.260 回答