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
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 guaranteeObject<string,string>
which is the reasonTypeScript
triggers an error.I created an example function to do the job.
The Code:
As
Headers
constructor is made out ofHeadersInit
,Or, if you want to support
undefined
,Or, if you want to support
undefined
returningundefined
,tests playground: