Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - "Authorization" does not exist on type HeadersInit

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)

like image 448
user3494322 Avatar asked Mar 11 '26 02:03

user3494322


1 Answers

Here is the solution:

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

Generally you want to avoid Type Assertion (as) if possible.

Alternative solution: if you know options.headers is neither a Headers or a string[][] you can do this:

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

or the equivalent

options.headers = {} as Record<string, string>
like image 91
Zoltán Dobrovolni Avatar answered Mar 13 '26 15:03

Zoltán Dobrovolni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!