Home > database >  Type '{}' is not assignable to type 'AxiosRequestHeaders'
Type '{}' is not assignable to type 'AxiosRequestHeaders'

Time:01-29

type here

I am working on a react application with typescript but I ran into an error with AxiosResquestHeader which keeps getting type not assignable. I'd wanted to get the current token for the signed-in user from localStorage. this is my AuthHeaders.ts


export default function authHeader(): AxiosRequestHeaders {
  type userToken = {
  accessToken: string;
};
  const localstorageUser = localStorage.getItem("user");
  if (!localstorageUser) {
    return {};
  }
  const user = JSON.parse(localstorageUser);
  if (user && user.token) {
    return { Authorization: `Token ${user.token}` };
  }
  return {};

}

and this gets called from AuthContext.ts as follows

export const AuthContextProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const navigate = useNavigate();
  const [user, setUser] = useState(() => AuthService.getCurrentUser());

  async function login(email: string, password: string) {
    const data = await AuthService.login(email, password);
    setUser(data);
    return data;
  }

  function logout() {
    AuthService.logout();
    setUser(null);
    navigate("/login");
  }

  // axios instance for making requests
  const authAxios = axios.create();

  // request interceptor for adding token
  authAxios.interceptors.request.use((config) => {
    // add token to request headers
   ** config.headers = authHeader();**
    return config;
  });

and this is the error that I get:

ERROR in src/services/AuthHeaders.ts:14:5

TS2322: Type '{ Authorization: string; }' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ Authorization: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.
    12 |   const user = JSON.parse(localstorageUser);
    13 |   if (user && user.token) {
  > 14 |     return { Authorization: `Token ${user.token}` };
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    15 |     // throw new Error('User Token Found');
    16 |   }
    17 |   // return {};


ERROR in src/services/AuthHeaders.ts:14:5

TS2322: Type '{ Authorization: string; }' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ Authorization: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.
    12 |   const user = JSON.parse(localstorageUser);
    13 |   if (user && user.token) {
  > 14 |     return { Authorization: `Token ${user.token}` };
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    15 |     // throw new Error('User Token Found');
    16 |   }
    17 |   // return {};

when I comment out the return methods in AuthHeaders.ts and replace them with throw new Error() the program seems to compile without any issues but of course, the logic is incorrect.

I am a bit new to typescript and react concepts but I am sure that this could be with typescript return types. Anyways I really need your help. Thanks

CodePudding user response:

You might want to use RawAxiosRequestHeaders instead of AxiosRequestHeaders.

AxiosRequestHeaders is a class inherited from AxiosHeaders which cannot be instantiated just from an object ({}).

RawAxiosRequestHeaders on the other hand is just an interface and probably fit for what you're trying to achieve here.

CodePudding user response:

I see that you are just returning an object that contains the authorization token. For that, the return type of authHeader need not necessarily be AxiosRequestHeaders

You can use this in the function's return type.

type userToken = {
  accessToken: string;
}

export default function authHeader(): {Authorization: string} | {} {
}

type userToken = {
  accessToken: string;
};

export default function authHeader(): {Authorization: string} | {} {
  const localstorageUser = localStorage.getItem("user");
  const user = JSON.parse(localstorageUser);
  if (user && user.token) {
    return { Authorization: `Token ${user.token}` };
  }
  return {};
}
  • Related