【问题标题】:How to make header object in TypeScript?如何在 TypeScript 中创建标头对象?
【发布时间】:2022-12-30 12:21:03
【问题描述】:

如果我创建 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,
}

【问题讨论】:

标签: typescript axios


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    @coglialoro 解决方案仍然有错误,通过使用这个符号解决了它:

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

    【讨论】:

      猜你喜欢
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多