I'm using the node-fetch
npm module and have a helper function for making authorized requests to a third party service (basically just middleware for adding in the Authorization header).
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)
}
The RequestInit
type is defined as having a headers
property of type HeadersInit
defined as the following
export type HeadersInit = Headers | string[][] | { [key: string]: string };
I get two distinct errors in my IDE (VSCode) and tsc
refuses to compile this because
Property 'Authorization' does not exist on type 'Headers'.ts(2339)
and
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)
Now obviously "User-Agent" and "Authorization" are valid http headers, and from my understanding the type {[key: string]: string}
definition should allow for this since "User-Agent" and "Authorization" are strings and their values are being set as strings. Why is tsc not able to see this and how can I actually fix it?
(I've used //@ts-ignore
on the affected lines in the past, but I'd like to understand what its concerned about and how to fix this in the future - because having ts-ignore all over the codebase does not look professional)
HeadersInit
andHeaders
are two different things. Thanks! – Comatose