我正在為 Angular 的 HttpClient 撰寫一個配接器,我需要兩個不同的 get 函式。一個回傳 Blob,一個回傳泛型。但是當我嘗試實作它時,我得到了錯誤:
TS2393:重復的功能實作。
get<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
context?: HttpContext;
observe?: 'body';
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T> {
return this.handleRequest(this.http.get<T>(url, options));
}
get(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'response';
context?: HttpContext;
params?: HttpParams | {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};
reportProgress?: boolean;
responseType: 'blob';
withCredentials?: boolean;
}): Observable<HttpResponse<Blob>> {
return this.handleRequest(this.http.get(url, options));
}
當 HttpClient 類中的 get 函式的實際實作看起來幾乎相同時,我不明白這是一個錯誤。
uj5u.com熱心網友回復:
您不能在 javascript 中擁有兩個具有相同名稱(并且在相同范圍內)的函式。相反,您必須創建一個函式來計算出您擁有哪些引數并做正確的事情,然后使用 typescript 您可以撰寫兩個不同的函式簽名來獲取正確的型別,例如:
get<T>(url: string, observe: 'body'): Observable<T>;
get(url: string, observe: 'response'): Observable<HttpResponse<Blob>>;
get(url: string, observe: 'body' | 'response') {
if (observe === 'body') {
// ... implementation
} else {
// ... implementation
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495088.html
標籤:javascript 有角度的 打字稿
