axios 如何在TypeScript中创建头对象?

7cjasjjr  于 2023-01-02  发布在  iOS
关注(0)|答案(2)|浏览(228)

如果我生成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; }'.

我该怎么解决这个问题呢?是不是一个预先定义的axios类型的头文件?

axios({
    // ..
    headers: headers,
})
    .then((resp: any) => {
    })
    .catch((err) => console.error(err))

--
有没有比这更简单的方法?

let headers: {
    [key: string]: string | boolean
} = {
    'Content-Type': 'application/json',
    crossDomain: true,
}
xnifntxz

xnifntxz1#

您可以从axios导入AxiosRequestHeaders,并使用它来键入headers变量,如下所示:

import { AxiosRequestHeaders } from 'axios';
let headers: AxiosRequestHeaders = {
  'Content-Type': 'application/json',
  crossDomain: true,
};

顺便说一句,如果你去看看类型定义,你会发现它和你的尝试非常相似:

type AxiosRequestHeaders = {
  [x: string]: string | number | boolean;
}
r7knjye2

r7knjye22#

@coglialoro解决方案仍然有错误,使用以下符号解决:

import type { AxiosRequestHeaders } from 'axios';
let headers = {
  'Content-Type': 'application/json',
  crossDomain: true,
} as AxiosRequestHeaders;

相关问题