【问题标题】:Duplicate function implementation in TypescriptTypescript 中的重复函数实现
【发布时间】:2022-06-23 22:48:05
【问题描述】:

我正在为 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 函数的实际实现看起来几乎相同时,我不明白这是一个错误。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    在 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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2021-02-27
      相关资源
      最近更新 更多