typescript 如何处理键入可能是成功或错误的响应?

oxf4rvwz  于 2023-01-10  发布在  TypeScript
关注(0)|答案(2)|浏览(109)

我有这样的代码:

socket.emit(ClientActions.LOAD_GAME_STATE, (response: GameState | ErrorResponse) => {
       // use response
});

问题是,如果我试图访问GameState对象上的属性,它会不出所料地给我一个错误,因为这些属性在ErrorResponse类型上不存在。
我该如何表达响应可能是数据或错误,并相应地输入和使用它?有推荐的方法吗?

hpcdzsge

hpcdzsge1#

这是推荐的输入方式,要将类型缩小到success或error,应该使用if语句作为类型保护:

socket.emit(ClientActions.LOAD_GAME_STATE, (response: GameState | ErrorResponse) => {
    if ('<a property only in ErrorResponse>' in response) {
       // response is of type `ErrorResponse`
    } else {
       // response is of type `GameState`
    }
});
cclgggtu

cclgggtu2#

对于更具内聚性和可扩展性的类型,我建议如下(具体取决于您的实现)

type ResponseTypes = "success" | "error"; // You may want to get more specific/granular here

interface SocketResponse {
  type: ResponseTypes;
  // Other info on every socket response
}

interface SocketError extends SocketResponse {
  type: "error";
  errorMessage: string;
}

interface SocketGameState extends SocketResponse {
  type: "success";
  gameState: GameState;
}

你的原始代码会变成

socket.emit(ClientActions.LOAD_GAME_STATE, (response: SocketGameState | SocketError) => {
  if (response.type === "error") {
    ... // Narrows to SocketError
  } else {
    ... // Narrows to SocketGameState
  }
});

我认为这个解决方案将允许您最灵活地添加许多新类型的响应类型,同时以一致的、直观类型化的方式处理错误。

相关问题