【发布时间】: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