union类型在redux saga操作类型中不起作用?

时间:2019-08-24 15:53:18

标签: 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;
  };
}

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; }'

如何在打字稿中修复它?

1 个答案:

答案 0 :(得分:1)

传递给createBoard传奇的动作实际上不是联合类型。 action参数只能是createBoardRequest,因此您的类型应该是

export function* createBoard(action: createBoardRequest) {
  ...

在您的原始代码中,由于您键入了要传递给action的{​​{1}}作为联合类型,因此,如果createBoardaction,则打字稿会正确地引发错误则createBoardSuccess将不存在。

您可能想在任何化简器对action.payload.nameBoardsActionTypecreateBoardRequest作出响应的情况下使用createBoardSuccess类型,但不应该用来键入{{1 }} createBoardFailure故事的参数。