【发布时间】:2022-01-18 16:53:19
【问题描述】:
我目前正在开发一个 react typescript 应用程序,并且正在尝试正确键入我的 axios 拦截器。我似乎无法弄清楚如何破解这些类型。
TL;DR 问题:TS 无法正确识别我的 axios 拦截器响应配置类型。
我的代码 --拦截器创建
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;
使用 Axios 实例
// 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');
});
问题
正如您从我的代码 cmets 中看到的那样,TS 强制我键入保护类型“成功”场景(意味着请求没有失败),以确保它不是错误,这很烦人,因为我已经定义了什么类型应该是onSuccess。此外,我的 .catch 方法中没有任何类型定义。
我知道 Promise 可以在 .then 和 .catch 中返回错误,但是为什么我不能让 TS 弄清楚当我明确通过它时我将使用 .catch 来处理错误正确的打字?
感谢您的所有帮助!我真的在这里挣扎。关于 Axios TS 的讨论很多,但我似乎找不到这个。
【问题讨论】:
-
我没有使用 TS,但我找到了一个可能的解决方案:github.com/axios/axios/issues/1510#issuecomment-396894600
-
感谢@ag-dev,它很有帮助,但不完全是!感谢您的帮助!
标签: javascript reactjs angular typescript axios