Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequestHeaders

I am trying to assign headers to axios.get, below throws error.

import authHeader from './auth-header';

return axios.get(API_URL + 'user', { headers: authHeader() });

The function is as:

export default function authHeader() {
    const userStr = localStorage.getItem("user");
    let user = null;
    if (userStr)
      user = JSON.parse(userStr);
  
    if (user && user.accessToken) {      
      return { 'x-access-token': user.accessToken };
    } else {
      return {};
    }
  }

However, if I do something like the below it works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 return axios.get(API_URL + 'user', { headers: { 'Authorization': `token test` }});

What am I missing here?

>Solution :

The definition for Axios headers is…

type AxiosRequestHeaders = Record<string, string | number | boolean>;

TypeScript is not able to infer the correct return type from your code.

Simply set the appropriate return type on your function

export default function authHeader(): AxiosRequestHeaders {
  //...
}

An even better option would be to correctly type your "user" data

interface User {
  accessToken?: string
}

export default function authHeader(): AxiosRequestHeaders {
  const user = JSON.parse(String(localStorage.getItem("user"))) as User | null
  return user?.accessToken ? { "x-access-token": user.accessToken } : {}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading