[英]Typescript Redux Type error of action.payload in reducer file
[英]Typescript throws error when accessing payload in reducer
我有一个减速器,如果我尝试访问第二个 switch case 中有效负载中的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 案例可能的所有操作的联合。 但是打字稿抛出以下错误:
Property 'formError' does not exist on type '{} | FormErrorType'.
Property 'formError' does not exist on type '{}'
我该如何解决这个问题?
问题是解构。 当你这样做时, type
停止与payload
相关,不再作为联合判别式工作。 请直接使用action.type
和action.payload
。
switch (action.type) { // direct use
case actionTypes.SUBMIT_FORM_FAILURE:
return {
...state,
responseSubmitted: false,
formError: action.payload.formError, // direct use
};
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.