[英]How to typify axios request headers
I'm trying to send request via Axios and I want to typify request headers.我正在尝试通过 Axios 发送请求,并且我想指定请求标头。 But I get an error.
但我得到一个错误。
I've created an interface Headers and used it to declare variable this._apiHeaders
.我创建了一个接口 Headers 并用它来声明变量
this._apiHeaders
。
Error text:错误文字:
The "Headers" type cannot be assigned to the "AxiosRequestHeaders" type.
There is no index signature for the "string" type in the "Headers" type (ts2322)
interface Headers {
'X-Parse-Application-Id': string,
'X-Parse-REST-API-Key': string
}
const response: ITest = await axios.get(
this.formCorrectApiUrl(Endpoints.classes, DBObjectName),
{
headers: this._apiHeaders // Here I get error
}
);
Can someone please tell me how to fix the error and why it occures.有人可以告诉我如何修复错误以及它发生的原因。
This can be implemented through "extends"这可以通过“扩展”来实现
interface Headers extends AxiosRequestHeaders {
'X-Parse-Application-Id': string
'X-Parse-REST-API-Key': string
}
But I recommend making additionally the ability to create fields optional.但我建议另外使创建字段的能力成为可选的。
export type NonUndefined<T, E = undefined> = Pick<
T,
{
[Prop in keyof T]: T[Prop] extends E ? never : Prop
}[keyof T]
>
interface Headers extends AxiosRequestHeaders {
'X-Parse-Application-Id': string
'X-Parse-REST-API-Key': string
}
type AxiosHeaders = NonUndefined<Headers>
const headers: AxiosHeaders = {
'X-Parse-Application-Id': 'test',
}
Please try this请试试这个
import axios, { AxiosRequestHeaders } from 'axios';
await axios.get(url, { headers: (this._apiHeaders as any as AxiosRequestHeaders) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.