使用 react-redux 和 typescript 分派操作时无法访问 reducer 中有效负载的属性

Cannot get access to properties on payload in the reducers when dispatching actions using react-redux and typescript

在我的 reducer 中,我想访问有效负载 属性 来更新存储,但是 Typescript 似乎抱怨我想要访问的 属性 的类型。

//_constants.ts

export const resultsConstants = {
  STORE_RESULT: "STORE_RESULT",
  DELETE_RESULT: "DELETE_RESULT",
};

//_actiontypes.ts

import { resultsConstants } from "../../_constants";

export interface StoreResult {
  type: typeof resultsConstants.STORE_RESULT;
  payload: { value: number };
}

export interface DeleteResult {
  type: typeof resultsConstants.DELETE_RESULT;
  payload: {
    id: string;
  };
}

// results.actions.ts调度

export const storeResult = (val: number) => {
  return (dispatch: Dispatch<StoreResult>) => {
    dispatch({
      type: resultsConstants.STORE_RESULT,
      payload: { value: val },
    });
  };
};

export const deleteResult = (id: string) => {
  return (dispatch: Dispatch<DeleteResult>) => {
    dispatch({ type: resultsConstants.DELETE_RESULT, payload: { id: id } });
  };
};

export type ResultActionTypes = StoreResult | DeleteResult;

// reducer.ts

const initialState: StoredResults = {
  results: [],
};

export const results = (
  state = initialState,
  action: ResultActionTypes
): StoredResults => {
  switch (action.type) {
    case resultsConstants.DELETE_RESULT:
      return state;
    case resultsConstants.STORE_RESULT:
      const oldState = { ...state };
      oldState.results = state.results.concat(action.payload.value); /* cannot access this value here */
      return { ...state };
    default:
      return state;
  }
};

这是我从 TS 得到的错误:

Property 'value' does not exist on type '{ value: number; } | { id: string; }'.
  Property 'value' does not exist on type '{ id: string; }'.ts(2339)

即使我在 results.actions.ts 文件中组合了动作类型,它仍抱怨 value 属性 在调度函数传递的动作类型上不存在。

如有任何帮助或建议,我们将不胜感激!

谢谢!

编辑

通过进一步将操作类型接口拆分为有效负载接口,并在 reducer 中对有效负载进行类型转换,我使它起作用:

// results.types.ts

export interface StoreResultPayload {
  value: number;
}

export interface StoreResultType {
  type: typeof resultsConstants.STORE_RESULT;
  payload: StoreResultPayload;
}

// 结果。reducer.ts

const val = action.payload as StoreResultPayload;
oldState.results = state.results.concat(val.value);

这对我来说仍然是一种解决方法。由于操作类型与联合运算符相结合,打字稿不应该能够推断出有效负载吗?

试试这个,看看它是否有效

interface StorePayload {
  value: number;
}

interface DeletePayload {
  value: string;
}

export interface StoreResult {
  type: string;
  payload: StorePayload
}

export interface DeleteResult {
  type: string;
  payload: DeletePayload;
}

对有效负载对象进行类型转换(告诉 Typescript:“相信我,我知道我在做什么”)是我目前能找到的唯一解决方法。请参阅问题的编辑版本以获得答案。