Typing Axios interceptor (axios.create) response typescript definitions
I am currently working on a react typescript app and I'm trying to properly type my axios interceptor. I can't seem to figure out exactly how to crack the types.
TL;DR The Problem: TS not recognizing my axios interceptor response configuration types properly.
My Code --Interceptor creation
const client = axios.create({
baseURL: apiURL
});
export const api = < T,
D > ({ ...options
}: AxiosRequestConfig < D > ) => {
const token = getToken();
client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
const onSuccess = (response: AxiosResponse < T > ) => response;
const onError = (error: Error | AxiosError) => {
if (axios.isAxiosError(error)) {
if (error.response ? .status === 401) {
logout();
window.location.assign(window.location.href);
return Promise.reject({
message: 'Please re-authenticate.'
});
} else {
return error;
}
}
return error;
};
return client(options).then(onSuccess).catch(onError);
};
export default api;
Using the Axios Instance
// I created a generic shown in the previous code used to define the response type
api < USER > ({
url: 'auth/me'
})
.then((response) => { // Error | AxiosResponse<User>
// have to add typeguards for TS not to complain that it COULD be type ERROR
if (!(response instanceof Error)) {
setUser(response.data);
setStatus('success');
}
})
// here, TS doesn't know what this is at all ? err: any
.catch((err) => { //err: any
setError(err);
setStatus('rejected');
});
The Problem
As you can see from my code comments, TS FORCES me to type guard a type the "success" scenario (meaning the request didn't fail), to make sure it's not an error, which is annoying since I already defined what the types should be onSuccess
. Additionally, I'm not getting any Type definitions in my .catch
method.
I know that promises can return errors in both the .then
and the .catch
, but why can't I get TS to figure out that I will be using .catch
for errors when I have clearly passed it the proper typings?
Thanks for all your help! I'm really struggling here. There has been a good bit of discussion on Axios TS, but I can't seem to find this.
Helpful discussions: https://github.com/axios/axios/issues/4176
You shouldn't be returning the error return error;
in the API function which is why TypeScript is forcing you to check the type in the then
clause because it is expecting an error as a possible return type. Catch clause is only run when an error is thrown throw error
or when a promise is rejected Promise.reject
.