How to set default header in axios with Typescript

Viewed 7611

I want to set default header with axios in Typescript. Here is my function:

function setJwt(jwt: string | null) {axios.defaults.headers!.common["x-auth-token"] = jwt;}

This shows the following issue: enter image description here

How to solve that in Typescript?

3 Answers

I've fixed this by extending HeadersDefaults interface from axios.

 import axios, { HeadersDefaults } from 'axios' 

 interface CommonHeaderProperties extends HeadersDefaults {
   Authorization: string;
 }

 axiosInstance.defaults.headers = {
   Authorization: `Bearer authToken`
 } as CommonHeaderProperties;

I succeed to solve the problem. Well, headers property has a Record<string, string> type.

So, we should change the second generic type like this:

enter image description here

We cast to unknown first because we can't reconvert directy the type Record

You can try like below,

function setJwt(jwt: string | null) {

    if (axios.defaults?.headers && axios.defaults.headers.common) {
        axios.defaults.headers.common['x-auth-token'] = jwt;
    }

}
Related