我将Angular的HttpClient服务包装在我自己的方法中,但仍希望用户能够传递options
,但是我似乎找不到在我自己的方法参数定义中引用该类型的好方法。
例:
constructor(private http: HttpClient) {}
my_request<T = any>(endpoint: string, payload: T, options: WhatTypeHere = {}) {
return this.http.post<MyHttpResponse>(this.build_url(endpoint), this.build_payload(payload), {
...options,
withCredentials: true,
});
}
您可以看到我不知道该放在哪里的options
参数,my_request()
以便在使用my_request时可以强制执行。
这是HttpClient.post()
fyi的定义
post(url: string, body: any | null, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;
我知道我可以将整个定义复制粘贴到我的方法中,但是如果有某种方式可以引用它,我希望简洁明了,并且将来定义会更改。
我尝试过的不起作用的一件事是 options: HttpClient['post']['options']
有什么我可以用来引用该类型的东西吗?
在至少打字稿3.3(撰写本文时在操场上使用的版本)中,您可以提取的第3个参数的类型post
。请参见下面的精简示例:
interface A {
eh: number
}
function post(url: string, body: any | null, options?: {a: A}): void {}
// Create an alias for convenience
type PostOptions = Parameters<typeof post>[2];
let options: PostOptions;
options = {}; // Expected error: Property 'a' is missing in type '{}' but required in type '{ a: A; }'.
options = { a: {} }; // Expected error: Property 'eh' is missing in type '{}' but required in type 'A'.
options = {a: {eh: 10}} // Ahh... just right :)
更多说明:Parameters<T>
函数的参数类型T
为元组。typeof post
得到函数的类型,然后我们想要第三个参数,它是索引处元组中的类型2
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句