skip to Main Content

Long story short, I need to convert a RequestInit‘s headers into a different data type that another library can understand. This library expects the headers to be Object<string, string>. I was hoping I could simply do something like:

headers: {
 ...init?.headers,
},

As expected, it wasn’t this simple. I believe it’s because some of the values in init.headers are of type number. How can I convert these so that TypeScript won’t complain?

2

Answers


  1. TypeScript, headers and Objects

    You got the reason for the error right. Headers could contain non-string or multi-valued headers. Simply using init.headers in a new object won’t guarantee Object<string,string> which is the reason TypeScript triggers an error.

    I created an example function to do the job.

    The Code:

    const convertHeadersInitObject = (
        headersInit: HeadersInit | undefined
      ): Record<string, string> => {
        const headersObj: Record<string, string> = {};
    
    if (!headersInit) 
      return headersObj;
    
    if (headersInit instanceof Headers) {
      for (const [key, value] of headersInit.entries()) 
        headersObj[key] = value;
    } 
    
    else if (Array.isArray(headersInit)) {
      headersInit.forEach(([key, value]) => {
        headersObj[key] = String(value);
      });
    }
    
    else {
      for (const [key, value] of Object.entries(headersInit)) 
        headersObj[key] = String(value);
     }
    
     return headersObj;
    };
    
    Login or Signup to reply.
  2. As Headers constructor is made out of HeadersInit,

    function headersInitToRecord(headersInit: HeadersInit) {
        return Object.fromEntries(new Headers(headersInit).entries());
    }
    

    Or, if you want to support undefined,

    function headersInitToRecord1(headersInit?: HeadersInit | undefined) {
        // new Headers(undefined) is fine
        return Object.fromEntries(new Headers(headersInit).entries());
    }
    

    Or, if you want to support undefined returning undefined,

    function headersInitToRecord2(headersInit?: HeadersInit | undefined) {
        return headersInit && Object.fromEntries(new Headers(headersInit).entries());
    }
    

    tests playground:

    console.log(
        headersInitToRecord([['foo', 'bar']]),
        headersInitToRecord({foo: 'bar'}),
        headersInitToRecord(new Headers([['foo', 'bar']])),
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search