Typescript 联合类型在redux saga操作类型中不起作用?

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

我的联合类型是此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传奇中尝试使用的代码,这是我遇到问题的代码:

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