Typescript 联合类型在redux saga操作类型中不起作用?
我的联合类型是此BoardsActionType:Typescript 联合类型在redux saga操作类型中不起作用?,typescript,redux,redux-saga,Typescript,Redux,Redux Saga,我的联合类型是此BoardsActionType: interface createBoardRequest { type: typeof CREATE_BOARD_REQUEST; payload: { name: string; }; } interface createBoardSuccess { type: typeof CREATE_BOARD_SUCCESS; payload: { board: BoardType; }; } inter
interface createBoardRequest {
type: typeof CREATE_BOARD_REQUEST;
payload: {
name: string;
};
}
interface createBoardSuccess {
type: typeof CREATE_BOARD_SUCCESS;
payload: {
board: BoardType;
};
}
interface createBoardFailure {
type: typeof CREATE_BOARD_FAILURE;
payload: {
error: string;
};
}
export type BoardsActionTypes =
| createBoardRequest
| createBoardSuccess
| createBoardFailure;
这是我在redux传奇中尝试使用的代码,这是我遇到问题的代码:
export function* createBoard(action: BoardsActionTypes) {
try {
const {
data: { board }
} = yield call(Api.boards.createBoard, action.payload.name); // ERROR HERE
yield put({ type: CREATE_BOARD_SUCCESS, payload: { board } });
} catch (error) {
yield put({ type: CREATE_BOARD_FAILURE, error });
}
}
我在action.payload.name上得到了一个错误,它说
Property 'name' does not exist on type '{ name: string; } | { board: BoardType; } | { error: string; }'
如何在typescript中修复它?传递给
createBoard
saga的操作实际上不是联合类型。action
参数只能是createBoardRequest
,因此您的类型应该是
export function* createBoard(action: createBoardRequest) {
...
在您的原始代码中,因为您键入了作为联合类型传递给createBoard
的action
,typescript正确地引发了一个错误,因为如果action
是createBoardSuccess
,那么action.payload.name
将不存在
您可能希望在响应createBoardRequest
、createBoardSuccess
和createBoardFailure
的任何减速器中使用BoardsActionType
类型,但不应用于将操作
参数键入createBoard
saga