【发布时间】:2020-05-14 21:06:41
【问题描述】:
我有一个减速器,如果我尝试在 秒内访问 payload 中的 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 case 可能的所有操作的联合。但是 Typescript 抛出以下错误:
Property 'formError' does not exist on type '{} | FormErrorType'.
Property 'formError' does not exist on type '{}'
我该如何解决这个问题?
【问题讨论】:
标签: reactjs typescript redux react-redux reducers