[英]Typescript add static method to a method
我定義了一個包裝 fetch 的方法,以便自動處理某些邊緣情況並提供統一響應 class 警報系統。 我不想自動將響應解析為 json(該平台不僅會請求 JSON)並想出了添加到獲取方法的原型 a.json 調用以自動解析和強制 promise 的想法,但發現我調用 integratedFetch.json(//etc) 時無法使用原型。 是否可以添加這樣的 static 方法?
示例代碼:
const integratedFetch: (
input: RequestInfo,
init?: RequestInit | undefined,
options?: Partial<IntegratedFetchOptions>
) => Promise<Response> = (input, init, options) => {
return fetch(input, init).then(async (response) => {
const { status } = response;
const responseClass = getResponseClass(response);
if (responseClass) {
switch (Number(responseClass) as ResponseClass) {
case ResponseClass.Informational:
//etc
case ResponseClass.Successful:
//etc
default:
throw Error(`Response class ${responseClass} unrecognized`);
}
}
return Promise.resolve(response);
});
};
integratedFetch.prototype.json = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) =>
integratedFetch(input, init, options).then((response) => response.json() as Promise<T>);
預期用途為:
integratedFetch.json<MyType>(//request)
-vs-
integratedFetch(//request).then(r => r.json() as Promise<T>)
當前的問題是使用integratedFetch.json()
會給出錯誤“類型上不存在屬性‘json’(輸入:RequestInfo,init?:RequestInit | undefined,options?:Partial | undefined)=> Promise <.. .>'.ts(2339)"
只需將第二個 function 分配給第一個 function 的新屬性。Typescript 會跟蹤它。 無需調整prototype
。
const foo = () => 123
foo.bar = () => 'hello'
foo() // 123
foo.bar() // "hello"
事實證明我必須在這里對 typedef 更有創意......
type FetchParams = (input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<Response>;
type StaticParams = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<T>;
//Create an aggregate typedef which allows for the static methods on the object definition
type IntegratedFetch = FetchParams & { json: StaticParams };
const integratedFetch: IntegratedFetch = (input, init, options) => { //the previous implementation
integratedFetch.json = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) =>
integratedFetch(input, init, options).then((response) => response.json() as Promise<T>);
這避免了 TS2339 錯誤,並允許我使用分配給 function 定義的 static 方法!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.