Extending global var in TypeScript

Viewed 61

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?

0 Answers
Related