首页 > 解决方案 > 在 typescript 中输入检查 API 响应

问题描述

我很好奇当您期望某种类型作为 fetch / Axios / etc 的响应并且它的响应是不同类型时会发生什么。我可以检测到这种不匹配吗?

interface HttpResponse<T> extends Response {
  parsedBody?: T;
}
export async function http<T>( request: RequestInfo ): Promise<HttpResponse<T>> {
  const response: HttpResponse<T> = await fetch( request );
  response.parsedBody = await response.json();
  return response;
}

// example consuming code
const response = await http<number>(
  "https://thisURLdoesNotReturnANumber"
);

代码会抛出错误吗?会无声无息地过去吗?如何检测不匹配?

标签: javascripttypescriptasync-await

解决方案


您的打字稿代码在浏览器执行之前转换为javascript 。它看起来像这样:

export async function http( request ) {
  const response = await fetch( request );
  response.parsedBody = await response.json();
  return response;
}
const response = await http("https://thisURLdoesNotReturnANumber");

如您所见,没有类型。浏览器对 typescript 中定义的类型一无所知。

稍后您可能会或可能不会收到运行时错误。要尽早抛出,您需要自己在http<T>()函数内部实现运行时检查。
或者您可以使用第三方库来完成这项工作。那里有很多。


推荐阅读