0
votes

I want to override XMLHttpRequest.prototype.open in Typescript but that's failing for me, is there a workaround ?

(function(open) {
  XMLHttpRequest.prototype.open = (method, url, async, user, pass) => {
    url = new URL(url);
    if (window["_keycloak"] && window["_keycloak"].token)
      url.searchParams.set('token', window["_keycloak"].token);
    open.call(this, method, url, async, user, pass);
  };
})(XMLHttpRequest.prototype.open);

This is the error message I'm getting

[ts] Type '(method: any, url: any, async: any, user: any, pass: any) => void' is not assignable to type '{ (method: string, url: string): void; (method: string, url: string, async: boolean, username?: string, password?: string): void; }'.

2

2 Answers

3
votes

thanks to @Matt suggestion I came to find the solution. Actually if you look at the XMLHttpRequest interface you fund two implementations for the open method

open(method: string, url: string): void;
open(method: string, url: string, async: boolean, username?: string | null, password?: string | null): void;

so the solution was to override the first one by adding optional parameters. this is the final solution:

(function(open) {
  XMLHttpRequest.prototype.open = (method: string, url: any , async?: boolean, username?: string, password?: string) => {
    url = new URL(url);
    if (window["_keycloak"] && window["_keycloak"].token)
    url.searchParams.set('token', window["_keycloak"].token);
    open.call(this, method, url, async, username, password);
  };
})(XMLHttpRequest.prototype.open);

Making async, username and password optionals solved it.

0
votes

If you look at the error message, the username and password parameters to the original XMLHttpRequest.prototype.open are optional (? mark), but in your implementation, they are required, so your implementation is not type-compatible with callers that omit those arguments. Just mark your user and pass parameters optional.