2

I'm trying to implement a Response.json static method polyfill. Response (not the interface, the class/constructor) is declared in lib.dom.d.ts. If it was defined with an interface like this:

declare var Response: ResponseConstructor;

interface ResponseConstructor {
  prototype: Response;
  new (body?: BodyInit | null, init?: ResponseInit): Response;
  error(): Response;
  redirect(url: string | URL, status?: number): Response;
};

I could have easily extended it in my own d.ts like this:

declare global {
  interface ResponseConstructor {
    json(data: any, init?: ResponseInit): Response;
  };
}

But it's defined like this instead:

declare var Response: {
  prototype: Response;
  new (body?: BodyInit | null, init?: ResponseInit): Response;
  error(): Response;
  redirect(url: string | URL, status?: number): Response;
};

Now when I try to extend it:

declare global {
  var Response: {
    json(data: any, init?: ResponseInit): Response;
  };
}

I get the following error:

Subsequent variable declarations must have the same type. Variable 'Response' must be of type '{ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number | undefined): Response; }', but here has type '{ json(data: any, init?: ResponseInit | undefined): Response; }'.

Playground reproduction

Is there a way to achieve what I'm trying to achieve?

cyco130
  • 4,654
  • 25
  • 34
  • 1
    GitHub issues at [ms/TS#4062](https://github.com/microsoft/TypeScript/issues/4062) and [ms/TS#37771](https://github.com/microsoft/TypeScript/issues/37771). There's no direct support for this; You could *try* using an [assertion function](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) like [this](https://tsplay.dev/wgZabW), but that only works in the scope the function is called in. Maybe the right thing is to just change lib.dom.d.ts locally (maybe with `ResponseConstructor`) and try to advocate for upstream changes? – jcalz Jun 24 '22 at 19:24
  • Yeah, I though that much. Thank you for digging up the issues which I failed to find! – cyco130 Jun 25 '22 at 15:00

0 Answers0