javascript - 在 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"
);
代码会抛出错误吗?会无声无息地过去吗?如何检测不匹配?
解决方案
您的打字稿代码在浏览器执行之前转换为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>()
函数内部实现运行时检查。
或者您可以使用第三方库来完成这项工作。那里有很多。
推荐阅读
- firebase - 如何配置链接到 Firebase 托管的域,并维护邮件访问(DNS 记录)
- javascript - 发布产品详细信息数组
- python - 匹配 Elastic Search 中的整个语句
- angular - 如果使用不存在的事件名称,Angular 不会显示错误
- caldav - PHP add calendar event using CalDav
- android - 如何使用 expo 更新 React 本机 android 应用程序
- java - 在 java 中有直接的用户输入
- javascript - How to load data from json file to bootstrap grid
- react-native - VS Code adds new line after < symbol on save
- django - django Multiple newtwork request to api cause unique violation error