打字稿为什么不能在函数中返回标题?



我是打字新手。我有一个值的头,我使用的工作很好。我试着把它分成另一个函数来调用,但是它不起作用。

下面是没有调用

的代码
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 })

当使用头作为参数执行.get时,此文件有效。但是当我试着把它变成一个函数。

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
}

抛出错误。

Type 'Record<string, string | null>' is not assignable to type 'AxiosRequestHeaders'.

'string'索引签名不兼容。类型'string | null'不能赋值给类型'string | number | boolean'。类型'null'不能赋值给类型'string | number | boolean'。

我怎样才能使它作为一个函数工作?

编辑:try catch块错误。固定。

编辑:从带有错误信息的注释中添加了更新的代码。

您试图将整个函数传递给axios配置,而不是使用该函数的结果。

试试这个:

axios.get("https://localhost:", { headers: getHeader() })

另一个注意事项,您的getHeader函数有一些小问题-

  • 可以用Record代替any
  • 你不应该将变量初始化为不同于你期望的类型-为什么是空的string?使用空对象代替
  • 最好使用constlet代替var
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
}

最新更新