在打字稿中对 API 响应进行类型检查

ilu*_*vAS 8 javascript async-await typescript

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

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"
);
Run Code Online (Sandbox Code Playgroud)

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

x00*_*x00 3

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

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

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

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