我目前正在開發一個反應打字稿應用程式,并且正在嘗試正確鍵入我的 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 FORCES me to type guard a type the "success" 場景(意味著請求沒有失敗),以確保它不是一個錯誤,這很煩人,因為我已經定義了什么型別應該是onSuccess。此外,我的.catch方法中沒有任何型別定義。
我知道 promise 可以在 the.then和中回傳錯誤.catch,但是為什么我不能讓 TS 弄清楚.catch當我清楚地傳遞了正確的型別時我將用于錯誤?
感謝你的幫助!我真的在這里掙扎。關于 Axios TS 的討論很多,但我似乎找不到這個。
有用的討論:https ://github.com/axios/axios/issues/4176
uj5u.com熱心網友回復:
您不應該return error;在 API 函式中回傳錯誤,這就是 TypeScript 強制您檢查then子句中的型別的原因,因為它期望錯誤作為可能的回傳型別。Catch 子句僅在拋出錯誤throw error或 promise 被拒絕時運行Promise.reject。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414474.html
標籤:
