首页 > 解决方案 > 使用 react-redux 和 typescript 调度操作时,无法访问减速器中有效负载的属性

问题描述

在我的减速器中,我想访问有效负载属性来更新商店,但 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;

// 减速器.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调度函数传递的动作类型上不存在该属性。

任何有关如何以不同方式进行操作的帮助或建议将不胜感激!

谢谢!

编辑

通过进一步将操作类型接口拆分为有效负载接口,并在减速器中对有效负载进行类型转换,我得到了这个工作:

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

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

标签: typescriptionic-frameworkreduxreact-reduxdispatch

解决方案


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

interface StorePayload {
  value: number;
}

interface DeletePayload {
  value: string;
}

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

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

推荐阅读