Angular – Typescript http.get Error: No overload matches this call

angulartypescript

I am trying to get a text file from the server so I have done this:

const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'text/html',
    'Content-Type': 'text/plain; charset=utf-8'
  }),
  responseType: 'text'
};
this.http.get<any>(url, httpOptions).subscribe(response => {
  const blob = new Blob([response], { type: 'text/csv' });
  const url = window.URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.download = 'user-permission-auditlog' + endDate.toUTCString() + '.csv';
  anchor.href = url;
  anchor.click();
});

And it works exactly the way I want it to. However the compiler cries out in pain:

error TS2769: No overload matches this call.
Overload 1 of 15, '(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }): Observable<…>', gave the following error.
Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.
Property 'observe' is missing in type '{ headers: HttpHeaders; responseType: string; }' but required in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe: "events"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'.

It lists 3 of the 15, all of them complaining that responseType should be 'json' but 'text' as a responseType is definitely one of the overloads:

get(url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType: "text"; withCredentials?: boolean; }): Observable<string>

https://angular.io/api/common/http/HttpClient#get

What am I doing wrong here?

Best Answer

Okay so the fix was to change the responseType to 'text' as 'json', then replace the return type of any to string (which is how it is determining which overload to use).

const httpOptions = {
  headers: new HttpHeaders({
    'Accept': 'text/html',
    'Content-Type': 'text/plain; charset=utf-8'
  }),
  responseType: 'text' as 'json'
};
this.http.get<string>(url, httpOptions).subscribe(response => {
  ...
});
Related Topic