访问 reducer 中的 payload 时 Typescript 抛出错误

Typescript throws error when accessing payload in reducer

我有一个减速器,如果我尝试访问 formError 属性 Typescript 会抛出一个错误 payloadsecond switch case.

import actionTypes, { ActionCreatorType, ReducerType } from './types';

const initialState: ReducerType = {
  formError: '',
  responseSubmitted: false,
};

const enquiryFormReducer = (state = initialState, action: ActionCreatorType): ReducerType => {
  const { type, payload, } = action;

  switch (type) {
    case actionTypes.SUBMIT_FORM_SUCCESS:
      return {
        ...state,
        responseSubmitted: true,
        formError: '',
      };

    case actionTypes.SUBMIT_FORM_FAILURE:
      return {
        ...state,
        responseSubmitted: false,
        formError: payload.formError,
      };

    default:
      return state;
  }
};

export default enquiryFormReducer;

这是我的 types 文件。

const actionTypes = {
  SUBMIT_FORM_SUCCESS: 'SUBMIT_FORM_SUCCESS',
  SUBMIT_FORM_FAILURE: 'SUBMIT_FORM_FAILURE',
} as const;

interface FormErrorType {
  formError: string;
}

export interface SuccessActionType {
  type: typeof actionTypes.SUBMIT_FORM_SUCCESS;
  payload: {};
}

export interface FailureActionType {
  type: typeof actionTypes.SUBMIT_FORM_FAILURE;
  payload: FormErrorType;
}

export interface ReducerType {
  responseSubmitted: boolean;
  formError: string;
}

export type ActionCreatorType = | SuccessActionType | FailureActionType;

export default actionTypes;

您可以看到 actionCreatorTypes 是根据 switch case 可能执行的所有操作的集合。但是 Typescript 抛出以下错误:

Property 'formError' does not exist on type '{} | FormErrorType'.
Property 'formError' does not exist on type '{}'

如何解决这个问题?

问题是解构。当你这样做时 type 停止与 payload 相关并且不再用作联合判别。请直接使用action.typeaction.payload

switch (action.type) { // direct use
    case actionTypes.SUBMIT_FORM_FAILURE:
      return {
        ...state,
        responseSubmitted: false,
        formError: action.payload.formError, // direct use
      };
    ...