【问题标题】:Typescript - "Authorization" does not exist on type HeadersInit打字稿 - HeadersInit 类型上不存在“授权”
【发布时间】:2021-07-24 12:58:57
【问题描述】:

我正在使用node-fetch npm 模块,并且有一个辅助函数用于向第三方服务发出授权请求(基本上只是用于添加授权标头的中间件)。

async function makeAuthorizedRequest(url: string, options: RequestInit) {
  if (!options) {
    options = { headers: {} as HeadersInit }
  }
  if (!options.headers) {
    options.headers = {} as HeadersInit
  }
  options.headers.Authorization = `Bearer ${access_token}`
  if (!options.headers['User-Agent']) {
    options.headers['User-Agent'] = USERAGENT
  }
  return fetch(url, options)
}

RequestInit 类型定义为具有 headers 类型的 HeadersInit 属性,定义如下

export type HeadersInit = Headers | string[][] | { [key: string]: string };

我的 IDE(VSCode)中有两个明显的错误,tsc 拒绝编译,因为

Property 'Authorization' does not exist on type 'Headers'.ts(2339)

Element implicitly has an 'any' type because expression of type '"User-Agent"' can't be used to index type 'HeadersInit'.
  Property 'User-Agent' does not exist on type 'HeadersInit'.ts(7053)

现在显然 "User-Agent" 和 "Authorization" 是有效的 http 标头,据我了解,{[key: string]: string} 类型定义应该允许这样做,因为 "User-Agent" 和 "Authorization" 是字符串,它们的值是设置为字符串。为什么 tsc 看不到这一点,我该如何解决?

(我过去在受影响的线路上使用过//@ts-ignore,但我想了解它关注的问题以及将来如何解决这个问题 - 因为在代码库中使用 ts-ignore 并不会看起来很专业)

【问题讨论】:

    标签: typescript node-fetch


    【解决方案1】:

    解决办法如下:

    const headersInit: HeadersInitt = {};
    options.header = headersInit;
    

    一般情况下,如果可能,您希望避免使用类型断言 (as)。

    替代解决方案:如果您知道options.headers 既不是Headers 也不是string[][] ,您可以这样做:

    options.headers = {} as { [key: string]: string }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 2017-03-02
      • 2021-09-07
      • 2017-08-07
      • 2017-03-26
      • 2017-09-06
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多