我希望能夠在使用型別引數的異步函式中引發錯誤。這滿足所有打字要求:
function foo<T>(bar: T): Promise<T> {
return new Promise(() => bar);
}
這不會:
function foo<T>(bar: T): Promise<T> {
return new Promise(() => bar).catch((error) => throw new Error('Some error'));
}
這導致的 TypeScript 錯誤是:
Type 'Promise<unknown>' is not assignable to type 'Promise<T>'.
Type 'unknown' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'unknown'.ts(2322)
這是上述情況的真實場景,我將 Axios 特定的 HTTP 錯誤重新打包為供應商中立的東西:
async get<T>(path: string, query: Record<string, string>): Promise<HttpResponse<T>> {
return this.instance
.get(path, {
params: query,
})
.then((response) => this.mapToHttpResponse(response))
.catch((error) => throw new HttpError(error.response.status));
}
在使用型別引數的函式中拋出錯誤的正確方法是什么?
uj5u.com熱心網友回復:
在您給出的最小復制中,您應該在Promise建構式中指定泛型引數:
function foo<T>(bar: T): Promise<T> {
return new Promise<T>(() => bar).catch((error) => { throw new Error('Some error') });
}
TypeScript Playground 鏈接
但是,使用axios. 這是我將使用您給定的代碼執行的操作。請注意,這HttpResponse只是我創建的一個簡單的包裝器:
import axios from "axios";
import type { AxiosResponse } from "axios";
type HttpResponse<T> = { foo: T };
class MyHttpWrapper {
instance = axios.create();
mapToHttpResponse<T>(response: AxiosResponse<T>): HttpResponse<T> {
return { foo: response.data };
}
async get<T>(path: string, query: Record<string, string>): Promise<HttpResponse<T>> {
return this.instance
.get(path, {
params: query,
})
.then((response) => this.mapToHttpResponse(response))
.catch((error) => { throw new Error(error.response.status) });
}
}
uj5u.com熱心網友回復:
自己用try/catch.
async get<T>(path: string, query: Record<string, string>): Promise<HttpResponse<T>> {
try {
return await this.instance
.get(path, {
params: query,
})
.then((response) => this.mapToHttpResponse(response));
} catch (error) {
throw new HttpError(error.response.status);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442531.html
標籤:打字稿
上一篇:不能使用命名空間“API”作為值
