在减速器中访问有效负载时,打字稿会引发错误

时间:2020-01-29 11:15:18

标签: reactjs typescript redux react-redux reducers

我有一个减速器,如果我尝试在秒内访问有效载荷中的 formError 属性,则 Typescript 会引发错误开关盒

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;

这是我的类型文件。

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情况可以进行所有动作的并集。但是 Typescript 会引发以下错误:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

问题在于解构。这样做时,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
      };
    ...