如何在TypeScript中获取Axios响应头并解决类型报错问题
解决Axios响应头TypeScript类型报错问题
问题场景
发起REST请求后要检查并存储指定响应头,写了如下代码:
private getHeader(response: AxiosResponse) { if (response.headers.has('myheader')) { storeHeader(response.headers['myheader']); } }
但TypeScript抛出三个错误:
- TS18049: 'response.headers.has' 可能为 'null' 或 'undefined'
- TS2723: 无法调用可能为 'null' 或 'undefined' 的对象
- TS2349: 该表达式不可调用。类型 'string | number | boolean | AxiosHeaders | string[] | ((header: string, matcher?: true | AxiosHeaderMatcher | undefined) => boolean)' 的部分成员不可调用,类型 'string' 没有调用签名
问题原因
Axios的response.headers类型是AxiosResponseHeaders,它是AxiosHeaders | Record<string, string | string[]>的联合类型:
- 若为普通键值对对象(Record类型),本身没有
has方法 - 类型标注存在
null/undefined的可能性,TS会做严格校验
解决方案
方案1:用in操作符直接检查(最简单)
直接通过对象属性存在性检查,避开has方法的类型问题:
private getHeader(response: AxiosResponse) { // 先确保headers存在,再检查目标头是否在对象中 if (response.headers && 'myheader' in response.headers) { storeHeader(response.headers['myheader']); } }
方案2:先判断是否为AxiosHeaders实例
如果一定要用has方法,先确认headers是AxiosHeaders类型:
import { AxiosHeaders } from 'axios'; private getHeader(response: AxiosResponse) { if (response.headers instanceof AxiosHeaders && response.headers.has('myheader')) { storeHeader(response.headers.get('myheader')); } }
这里用get方法获取值,更符合AxiosHeaders的规范用法。
方案3:强制转换为AxiosHeaders(不推荐)
如果能100%确定响应头是AxiosHeaders类型,可以强制跳过类型检查:
private getHeader(response: AxiosResponse) { const headers = response.headers as AxiosHeaders; if (headers?.has('myheader')) { storeHeader(headers.get('myheader')); } }
这种方式会绕过TS的类型校验,仅适用于场景明确的情况。
内容的提问来源于stack exchange,提问作者Little Monkey
相关产品推荐
相关产品推荐

