Nisha Patel
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> {
This neither :
But this compiles and works :
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
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'.
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?