如何在Typescript中使用不同的签名按名称调用方法?

时间:2018-04-27 18:22:35

标签: javascript angular algorithm typescript angular-http

我试图设置一个方法来调用我的后端并为我做一些通用的东西。

所以我来看看这段代码:

this._http[type](url, params, options)

但是我发现4方法是多余的,我想知道是否有办法直接这样做:

Cannot invoke an expression whose type lacks a call signature

但是我收到了这个错误:

AND

因为 GET DELETE 在签名中没有 HttpParams

他们是否可以根据条件返回参数?或者返回两个参数并与签名匹配?

3 个答案:

答案 0 :(得分:1)

您可以使用.length property of a function返回所需参数数量的事实,并执行以下操作:

(this._http[type].length === 3 ? 
    this._http[type](url, params, options) : 
    this._http[type](url, options));

答案 1 :(得分:0)

您可以组合捕获类型,声明合并和映射类型的帮助程序,以实现所需的效果。不幸的是

type Method = 'post' | 'put' | 'delete' | 'get';

type R = {
    [M in Method]: (this: { http: HttpClient }, method: M) => typeof this['http'][M]
};

interface MyHttp extends R { }

class MyHttp {
    constructor(http: HttpClient) {
        Object.assign(
          this, (<Method[]>['get', 'post', 'put', 'delete'])
            .map(method => http[method].bind(http))
        );
    }
}

答案 2 :(得分:0)

我相信使用函数重载会得到你想要的东西:

myFct<T>(type: "get" | "delete", url: string, options: any): Observable<HttpEvent<T>>;
myFct<T>(type: "post" | "put", url: string, params: HttpParams, options: any): Observable<HttpEvent<T>>;
myFct<T>(type: "get" | "delete" | "post" | "put", url: string, paramsOrOptions: HttpParams | any, options?: any): Observable<HttpEvent<T>> {
    return type == "get" || type == "delete"
        ? this._http[type](url, paramsOrOptions)
        : this._http[type](url, paramsOrOptions, options) 
}


http.myFct<any>("get", "http://", {}) // OK
http.myFct<any>("get", "http://", {}, {}) // Error (too many args)
http.myFct<any>("post", "http://", {}, {}) // OK
http.myFct<any>("post", "http://", {}) // Error (too few args)

虽然,就个人而言,我不确定这只不过只有4个功能。