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:
How to solve that in Typescript?
CodePudding user response:
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:
We cast to unknown
first because we can't reconvert directy the type Record
CodePudding user response:
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;
}
}