typescriptaxios

How to make header object in TypeScript?


If I make the headers and would change conditionally:

let headers = {
    'Content-Type': 'application/json',
    crossDomain: true,
}
if (authnRes?.data?.jwt) {
    headers['Authorization'] = `Bearer ${authnRes?.data?.jwt}`
}

I will get an error:

Element implicitly has an 'any' type because expression of type '"Authorization"' can't be used to index type '{ 'Content-Type': string; crossDomain: boolean; }'.
  Property 'Authorization' does not exist on type '{ 'Content-Type': string; crossDomain: boolean; }'.

How can I solve it? Is it maybe a predefined axios type for Headers?

axios({
    // ..
    headers: headers,
})
    .then((resp: any) => {
    })
    .catch((err) => console.error(err))

--

Is it any easier way then this below?

let headers: {
    [key: string]: string | boolean
} = {
    'Content-Type': 'application/json',
    crossDomain: true,
}

Solution

  • You can import AxiosRequestHeaders from axios and use it to type your headers variable, like so :

    import { AxiosRequestHeaders } from 'axios';
    let headers: AxiosRequestHeaders = {
      'Content-Type': 'application/json',
      crossDomain: true,
    };
    

    By the way, if you go and look at the type definition you'll see it's very similar to your attempt:

    type AxiosRequestHeaders = {
      [x: string]: string | number | boolean;
    }