如何在 TypeScript 中制作 header object?
How to make header object in TypeScript?
如果我制作 headers
并有条件地更改:
let headers = {
'Content-Type': 'application/json',
crossDomain: true,
}
if (authnRes?.data?.jwt) {
headers['Authorization'] = `Bearer ${authnRes?.data?.jwt}`
}
我会得到一个错误:
Element implicitly has an 'any' type because expression of type '"Authorization"' can't be used to index type '{ 'Content-Type': string; crossDomain: boolean; }'.
Property 'Authorization' does not exist on type '{ 'Content-Type': string; crossDomain: boolean; }'.
我该如何解决?它可能是 Headers 的预定义 axios
类型吗?
axios({
// ..
headers: headers,
})
.then((resp: any) => {
})
.catch((err) => console.error(err))
--
有比下面这个更简单的方法吗?
let headers: {
[key: string]: string | boolean
} = {
'Content-Type': 'application/json',
crossDomain: true,
}
您可以从 axios
导入 AxiosRequestHeaders
并使用它来键入您的 headers
变量,如下所示:
import { AxiosRequestHeaders } from 'axios';
let headers: AxiosRequestHeaders = {
'Content-Type': 'application/json',
crossDomain: true,
};
顺便说一下,如果您查看类型定义,您会发现它与您的尝试非常相似:
type AxiosRequestHeaders = {
[x: string]: string | number | boolean;
}
如果我制作 headers
并有条件地更改:
let headers = {
'Content-Type': 'application/json',
crossDomain: true,
}
if (authnRes?.data?.jwt) {
headers['Authorization'] = `Bearer ${authnRes?.data?.jwt}`
}
我会得到一个错误:
Element implicitly has an 'any' type because expression of type '"Authorization"' can't be used to index type '{ 'Content-Type': string; crossDomain: boolean; }'.
Property 'Authorization' does not exist on type '{ 'Content-Type': string; crossDomain: boolean; }'.
我该如何解决?它可能是 Headers 的预定义 axios
类型吗?
axios({
// ..
headers: headers,
})
.then((resp: any) => {
})
.catch((err) => console.error(err))
--
有比下面这个更简单的方法吗?
let headers: {
[key: string]: string | boolean
} = {
'Content-Type': 'application/json',
crossDomain: true,
}
您可以从 axios
导入 AxiosRequestHeaders
并使用它来键入您的 headers
变量,如下所示:
import { AxiosRequestHeaders } from 'axios';
let headers: AxiosRequestHeaders = {
'Content-Type': 'application/json',
crossDomain: true,
};
顺便说一下,如果您查看类型定义,您会发现它与您的尝试非常相似:
type AxiosRequestHeaders = {
[x: string]: string | number | boolean;
}