I am new to typescript. I have a value for headers that I was uses that worked fine. I tried separating it into another function that would be called, but then it doesn't work.
Here is the code without being called
var headers: any = "";
try {
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
} catch (err) {
console.log(err);
}
axios
.get("https://localhost:", { getHeader })
This worked file when doing a .get with headers as a parameter. But when I try to turn it into a function.
export function getHeader () {
let headers: Record<string, string | null> = {}; // this line
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
return headers
}
It throws an error.
Type 'Record<string, string | null>' is not assignable to type 'AxiosRequestHeaders'.
'string' index signatures are incompatible. Type 'string | null' is not assignable to type 'string | number | boolean'. Type 'null' is not assignable to type 'string | number | boolean'.
How can I just make it work as a function?
Edit: The try catch block was incorrect. Fixed it.
Edit: Added the updated code from comments with the error message.
CodePudding user response:
You are trying to pass the entire function to the axios config, instead of using the result of that function.
Try this instead:
axios.get("https://localhost:", { headers: getHeader() })
On a different note, you have small problems in your getHeader
function -
- You can use
Record
instead ofany
- You shouldn't initialize the variable as a different type than what you expect - why an empty
string
? Use an empty object instead - It's preferable to use
const
orlet
instead ofvar
export function getHeader () {
let headers: Record<string, string> = {}; // this line
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
} catch (err) {
console.log(err);
}
return headers
}