I am using axios to talk to my APIs, and I wrapper it with a HTTClient class to avoid depend much on it:
import axios, { AxiosInstance } from 'axios';
import https from 'https';
import { stringify } from 'qs';
class HttpClient {
private static instance: AxiosInstance;
constructor() {
const axiosInstance = axios.create({
baseURL: process.env.ENDPOINT_API,
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
});
axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axiosInstance.defaults.paramsSerializer = this.paramsSerializer;
axiosInstance.defaults.withCredentials = true;
axiosInstance.interceptors.response.use((response) => response.data);
HttpClient.instance = axiosInstance;
}
public static getInstance = () => {
if (!HttpClient.instance) new HttpClient();
return HttpClient.instance;
};
private paramsSerializer = (params) => stringify(params, { arrayFormat: 'repeat' });
}
export default HttpClient.getInstance();
As you will notice, when I do
axiosInstance.interceptors.response.use((response) => response.data);
I'm returning the content of data. The issue is that now the type of the response is wrong.
interface TypedResponse {
name: string
}
const response = await HttpClient.put<TypedResponse>(`/`);
const response.name // Property 'name' does not exist on type 'TypedResponse'.ts(2339)
TypeScript is thinking that name is within data, like this:
// Response
{
data: {
name: string;
}
}
Which of course is wrong, as I'm not returning data anymore:
// Response
{
name: string
}
How can I change the default axios response type in my class?