请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

Axios interceptor 修改了 response 之后的类型推导

老师,我们在 axios 的 response 拦截器中修改了它的返回值,如果status等于200则直接返回response.data中的内容。
但是在类型推导中还是推导成AxiosResponse类型,而不是AxiosResponse.data的类型。
图片描述
图片描述

我看到axios库中有关于这个问题的issue -> Axios issue about response type

但是这个解决方案适用于统一返回response.data的情况。

如何才能在interceptors.response中根据 response.status的不同推导出正确的类型?

正在回答 回答被采纳积分+3

1回答

Brian 2022-12-12 19:43:17

覆盖呀,可以在utils里面改成这样:

declare module 'axios' {
   export interface AxiosResponse<T = any> extends Promise<T> {}
}

然后接口可以这么改:

export const signin = (username: string, password: string, ...rest: any) =>
    axios.post<any, AxiosResponse<{ access_token: string }, any>>(
    '/auth/signin',
    {
        username,
        password,
        ...rest,
    }
);

效果:

https://img1.sycdn.imooc.com//szimg/639713cc09e91b0211630324.jpg

0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号