Home > database >  Duplicate function implementation in Typescript
Duplicate function implementation in Typescript

Time:06-24

I am writing an adapter for the HttpClient from Angular and I need two distinct get functions. One that returns a Blob and one that returns a generic. But when I try to implement it, I get the error:

TS2393: Duplicate function implementation.

  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));
  }

I don't understand that this is an error when the actual implementation of the get functions in the HttpClient class looks almost the same.

CodePudding user response:

You cannot have two functions with the same name (and within the same scope) in javascript. You must instead make a single function that can work out which arguments you have and do the right thing, then with typescript you can write two different function signatures to get the types correct e.g.:

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
  }
}
  • Related