Reputation: 25661
Axios defines ResponseType
as
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream'
I'm trying to pass a configuration to axios.post
const config = {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': HOST_HEADER,
},
responseType: 'json'
}
const data_to_post = { .... omitted ... }
return axios.post(HOST, data_to_post, config)
Problem: typescript linter warn me saying the type string cannot be assigned to type ResponseType.
Also tried: Of course I cannot use the syntax
responseType: ResponseType.json
How can I fix this?
Upvotes: 3
Views: 8339
Reputation: 6253
The problem is that Typescript will infer config
to be of type
{
headers: {
'X-Requested-With': string;
'Content-Type': string;
'Host-Header': string;
};
responseType: string;
}
Typescript does not know that you are trying to create a config object for Axios. You can explicitly type the entire object as AxiosRequestConfig
, or you could explicitly type responseType: 'json'
to be of type ResponseType
.
const config: AxiosRequestConfig = {
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded',
'Host-Header': 'dsa',
},
responseType: 'json'
};
Upvotes: 6
Reputation: 25661
Fixed using explicit casting
responseType: <ResponseType> 'json'
Upvotes: 3