I'm scrutinizing the docs for HttpClient
, focusing on the get(...)
method. I've prepared the following sample:
const headers: HttpHeaders = new HttpHeaders();
const observe: HttpObserve = null;
const params: HttpParams = new HttpParams();
const reportProgress = false;
const responseType = "json";
const withCredentials = true;
const options = {
headers, observe, params,
reportProgress, responseType, withCredentials
};
this.http.get(url, options)
I get an error stating the following.
No overload matches this call.
The last overload gave the following error.
Argument of type '{ responseType: string; ... }'
is not assignable to parameter of type '{ responseType?: "json" | undefined; ... }'.
Types of property 'responseType' are incompatible.
Type 'string' is not assignable to type '"json" | undefined'.
It's pretty obvious what's the reported issue. However, I don't see how what I typed is in validation towards what is required. If I type undefined
as the value for responseType
, the compiler is satisfied. In fact, the elaborated code samples (number 7, 8 and 12 through 15) explicitly state that it's the syntax to be used.
How is my "json"
not the required "json"
?
"json"
. – Liddy"json"
is astring
but not allstring
are"json"
. – Liddyjson
instead ofstring
. One workaround could beconst responseType = "json" as "json";
– Havstadconst responseType: "json" = "json";
- then the actual value gets checked (compareconst foo = "bar" as "baz"
). – Liddy{a:1}
)? Also,as "json"
felt unfamiliar to me. As far my competence reaches, there's noJson
type/class in TS. Or is it som black magic (black magic to ignorant me, that is) saying that the type is whatever, where said whatever happens to be "json" sequence of characters? – Familial"json"
. If you don't know whatas <type>
means read up on type assertions. You really need to know TS basics to be effective in Angular. – Liddy{ responseType }
widens to{ responseType: string }
- typescriptlang.org/play/index.html#code/…. – Liddyjson
here) with union types ("json" | "text" | ...
) akin to enums. So theresponseType
should have the exact string"json"
. But for some reason (which I too don't understand yet), it's being inferred as typestring
in your case. So one solution would be to assert the type using theas <type>
syntax or better as @Liddy suggested define the type before assigning the value:const responseType: "json" = "json";
. – Havstad