Home > Enterprise >  How to typify axios request headers
How to typify axios request headers

Time:06-21

I'm trying to send request via Axios and I want to typify request headers. But I get an error.

I've created an interface Headers and used it to declare variable 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.

CodePudding user response:

Please try this

import axios, { AxiosRequestHeaders } from 'axios';

await axios.get(url, { headers: (this._apiHeaders as any as AxiosRequestHeaders) })

CodePudding user response:

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',
}
  • Related