0

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.

1 Answer 1

1

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I mean I get it, since the transpiled javascript would look equal. But somehow it is okay for the HttpClient implementation
The HttpClient is implemented here: github.com/angular/angular/blob/… all the ones above are just function delcarations: they have no implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.