Question:
Fix: Strange compilation error with Typescript and Angular

Problem 

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 a variable as a second parameter in HttpClient.get()?


Thanks


Solutions

The >httpClient.get has a complex signature with 15 overloads.


A bunch of them depend 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, so TS can't find the right overload you're looking for.


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


const httpOptions = {

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

  responseType: 'text'

} as const


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers