我目前正在开发一个应用程序,我正在尝试正确地键入我的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');
});
问题
正如您从我的代码注释中看到的,TS强迫我输入一个类型为“成功”场景(这意味着请求没有失败),以确保它不是一个错误,这是恼人的,因为我已经定义了类型应该是onSuccess。此外,我不会在我的.catch方法中获得任何类型定义。
我知道承诺可以同时返回.then和.catch中的错误,但是为什么我不能让TS知道如果我清楚地传递了正确的类型,我就会使用.catch来处理错误?
谢谢你的帮助!我是,真的在这里挣扎。关于Axios TS已经有了很好的讨论,但我似乎找不到这个。
发布于 2022-01-18 07:42:55
您不应该在API函数中返回错误return error;,这就是为什么TypeScript强制您检查then子句中的类型,因为它期望错误作为可能的返回类型。只有在抛出throw error错误或拒绝承诺时才运行Catch子句,Promise.reject。
https://stackoverflow.com/questions/70751518
复制相似问题