我的联合类型是BoardsActionType:
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 saga中使用它,这是我的代码遇到了问题:
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; }'
如何在打字稿中修复它?
答案 0 :(得分:1)
传递给createBoard
传奇的动作实际上不是联合类型。 action
参数只能是createBoardRequest
,因此您的类型应该是
export function* createBoard(action: createBoardRequest) {
...
在您的原始代码中,由于您键入了要传递给action
的{{1}}作为联合类型,因此,如果createBoard
是action
,则打字稿会正确地引发错误则createBoardSuccess
将不存在。
您可能想在任何化简器对action.payload.name
,BoardsActionType
和createBoardRequest
作出响应的情况下使用createBoardSuccess
类型,但不应该用来键入{{1 }} createBoardFailure
故事的参数。