Skip to content

Commit c95b0bc

Browse files
fix: support objects with null prototype as HeadersInit (#81)
Currently, if an object is created with the null prototype, e.g. ```typescript const headers = Object.create(null); ``` attempting to instantiate a `Headers` object with this polyfill throws an error: ``` TypeError: Cannot read properties of undefined (reading 'name') ``` because `headers.constructor` is undefined. @kettanaito --------- Co-authored-by: Artem Zakharchenko <kettanaito@gmail.com>
1 parent 170cec2 commit c95b0bc

2 files changed

Lines changed: 8 additions & 1 deletion

File tree

src/Headers.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ describe('constructor()', () => {
4040
expect(headers.get('accept')).toEqual('*/*')
4141
})
4242

43+
it('can be created given an object with a null prototype', () => {
44+
const headersInit = Object.create(null)
45+
headersInit.accept = '*/*'
46+
const headers = new Headers(headersInit)
47+
expect(headers.get('accept')).toEqual('*/*')
48+
})
49+
4350
it('duplicates values for the same header names with different casing', () => {
4451
const headers = new Headers({
4552
'accept-encoding': 'gzip, deflate, br',

src/Headers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export class Headers {
2525
* `Headers` because that class may not be defined in Node or jsdom.
2626
*/
2727
if (
28-
['Headers', 'HeadersPolyfill'].includes(init?.constructor.name) ||
28+
['Headers', 'HeadersPolyfill'].includes(init?.constructor?.name) ||
2929
init instanceof Headers ||
3030
(typeof globalThis.Headers !== 'undefined' &&
3131
init instanceof globalThis.Headers)

0 commit comments

Comments
 (0)