如何在Typescript中获取Axios响应头

2hh7jdfx  于 2023-04-30  发布在  iOS
关注(0)|答案(1)|浏览(255)

我有一个休息呼叫,它可以发送回一个我想存储的标题。因此,我需要在分配它之前检查它是否在那里。
到目前为止,我做了这样的事情:

private getHeader(response: AxiosResponse) {
    if (response.headers.has('myheader')) {
      storeHeader(response.headers['myheader']);
    }
 }

但是Typescript抱怨response.headers.has。它说:

TS18049: 'response.headers.has' is possibly 'null' or 'undefined'.
TS2723: Cannot invoke an object which is possibly 'null' or 'undefined'.
TS2349: This expression is not callable.   Not all constituents of type 'string | number | boolean | AxiosHeaders | string[] | ((header: string, matcher?: true | AxiosHeaderMatcher | undefined) => boolean)' are callable.     Type 'string' has no call signatures.
tjrkku2a

tjrkku2a1#

AxiosResponse#headers的类型为RawAxiosResponseHeaders | AxiosResponseHeaders,AxiosResponseHeaders的类型为RawAxiosResponseHeaders & AxiosHeaders
方法has在类AxiosHeaders中定义,因此我们需要在使用headers instanceof AxiosHeaders调用has之前将response.headers缩小到AxiosHeaders

const headers = response.headers
if (headers instanceof AxiosHeaders && headers.has('myheader')) {
    storeHeader(headers['myheader']);
}

另一个答案的代码更少:-)

相关问题