Search code examples
angulartypescript

Strange compilation error with TypeScript and Angular


In an Angular application, I have a service with a method to get a simple string from a rest server. This code does not compile :

getText(): Promise<String> {
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'}),
      responseType: 'text'
    }    
    return firstValueFrom(this.httpClient.get(this.endPoint + this.publicUrl, httpOptions))
  }

This neither :

  getText(): Promise<String> {
    const httpOptions: Object = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'}),
      responseType: 'text'
    }    
    return firstValueFrom(this.httpClient.get(this.endPoint + this.publicUrl, httpOptions))
  }

But this compiles and works :

  getText(): Promise<String> {
    return firstValueFrom(this.httpClient.get(this.endPoint + this.publicUrl, {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'}),
      responseType: 'text'
    }))
  }

Why cannot I use variable as second parameter in HttpClient.get() ?


Solution

  • The httpClient.get has a complexe signature with 15 overloads.

    A bunch of them depens on the type of responseType.

    When you write

    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'}),
      responseType: 'text'
    }    
    

    httpOptions is inferred as {headers: HttpHeaders; responseType: string;}.

    As you can see responseType is widen to string, this is why TS isn't able to find the right overload you're looking for.

    Using as const can fix the issue here, responseType would not be widen anymore and defined as responseType: 'test'.

    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',  accept: 'text/plain'}),
      responseType: 'text'
    } as const