为什么axios拦截器中的config.headers可能为undefined?TS2532报错如何解决
TS2532 报错解决方案
报错原因
AxiosRequestConfig.headers的类型定义为可选属性AxiosRequestConfig.headers?: Record<string, string>,TypeScript 静态检查时判定该属性可能为undefined,直接访问其下的Authorization字段不符合类型安全规则,因此抛出该错误。
可用解决方法
- 方法1:先给headers做兜底赋值(最稳妥,无运行时风险)
先对headers做非空判断,为空时赋值为空对象,再写入Authorization字段:$api.interceptors.request.use((config) => { config.headers = config.headers ?? {} config.headers.Authorization= `Bearer ${localStorage.getItem('token')}` return config }) - 方法2:使用非空断言(仅适合确认运行时headers一定存在的场景)
用!非空断言运算符明确告诉TypeScript,headers属性不会为undefined,跳过静态检查:$api.interceptors.request.use((config) => { config.headers!.Authorization= `Bearer ${localStorage.getItem('token')}` return config }) - 方法3:创建Axios实例时初始化headers
实例化阶段就给headers赋默认空对象,后续所有请求的headers都默认存在,不会出现undefined的情况:const $api = axios.create({ withCredentials: true, baseURL: API_URL, headers: {} })
内容的提问来源于stack exchange,提问作者bluepuper
相关产品推荐
相关产品推荐

