1

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,
}
János
  • 32,867
  • 38
  • 193
  • 353
  • Does this answer your question? [How to conditionally add properties to a javascript object literal](https://stackoverflow.com/questions/21568760/how-to-conditionally-add-properties-to-a-javascript-object-literal) – Tobias S. Apr 27 '22 at 12:28
  • I think it is too complex what you shown – János Apr 27 '22 at 12:33

2 Answers2

1

Still got an error with @coglialoro solution, solved it by using this notation:

import type { AxiosRequestHeaders } from 'axios';
let headers = {
  'Content-Type': 'application/json',
  crossDomain: true,
} as AxiosRequestHeaders;
Freezystem
  • 4,494
  • 1
  • 32
  • 35
-1

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;
}
coglialoro
  • 601
  • 1
  • 4
  • 12