Home > Software engineering >  Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }'
Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }'

Time:12-01

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:

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

What am I missing here?

CodePudding user response:

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 } : {}
}
  • Related