我有這個代碼:
private descargar<T>(url: string, type: "arraybuffer" | "document" | "blob" | "json" | "text"): Promise<T | null>{
return new Promise(function (resolve) {
// Get file name from url.
var xhr = new XMLHttpRequest();
xhr.responseType = "blob"
xhr.onload = function () {
resolve(xhr.response);
return;
};
xhr.onerror = ()=>resolve(null);
xhr.open("GET", url);
xhr.send();
})
}
它被這樣呼叫:
const response = await this.descargar<Blob>(url, "blob")
這是多余的,因為您需要指定 Blob 兩次。有什么選擇?
uj5u.com熱心網友回復:
假設您定義了一個型別,該型別將可能提供給type引數的字串映射到其關聯型別:
type DescargarMap = {
arraybuffer: ArrayBuffer;
document: Document;
blob: Blob;
json: Object;
text: string;
}
(我對這些字串如何映射到型別進行了最佳猜測......可能需要修復)
現在,使用這種地圖型別,您可以按如下方式定義您的函式:
descargar<T extends keyof DescargarMap>(
url: string,
type: T): Promise<DescargarMap[T] | null>{...}
并稱之為
// `buf` is `ArrayBuffer | null`
const buf = await descargar("", "arraybuffer");
Now, appropriate options for the typeparameter are shown in code-completion hints of the IDE and the return-type is correctly mapped without having to supply the generic parameter.
游樂場鏈接
uj5u.com熱心網友回復:
class SomeClass {
private descargar(
url: string,
type: "arraybuffer"
): Promise<ArrayBuffer | null>;
private descargar(url: string, type: "document"): Promise<Document | null>;
private descargar(url: string, type: "blob"): Promise<Blob | null>;
private descargar(url: string, type: "text"): Promise<string | null>;
private descargar<T>(url: string, type: "json"): Promise<T | null>;
private descargar(
url: string,
type: "arraybuffer" | "document" | "blob" | "json" | "text"
): Promise<any | null> {
return new Promise(function (resolve) {
// Get file name from url.
var xhr = new XMLHttpRequest();
xhr.responseType = type;
xhr.onload = function () {
resolve(xhr.response);
return;
};
xhr.onerror = () => resolve(null);
xhr.open("GET", url);
xhr.send();
});
}
public async test() {
const buf = await this.descargar("/buf", "arraybuffer");
console.log(buf?.byteLength);
const object = await this.descargar<{ id: string; name: string }>(
"/text",
"json"
);
console.log(object?.id);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494531.html
上一篇:類java的多個泛型型別
