Search code examples
typescriptxmlhttprequest

How do I use XMLHttpRequest in Typescript?


This is a new situation for me, I have been using TypeScript for a long time but struggling with XMLHttpRequest.

request.open('GET', path);
request.onload = () => {
   // this is fine
}
request.onerror = (e: ErrorEvent) => {
   // i can't figure this out
   this.registerError(e);
}

How do I correctly deal with that error response? My code above fails during compilation with this:

error TS2322: Type (e: ErrorEvent) => void is not assignable to type (this: XMLHttpRequest, ev: ProgressEvent) => any

I wasn't expecting that.

If you change the code to

request.onerror = (this: XMLHttpRequest, ev: ProgressEvent) => {
};

It isn't valid typescript. Even if it was, this as a parameter name is incredibly confusing.

Would it be possible to provide an example of how to catch an XMLHttpRequest error?


Solution

  • The reason you can't specify this is because you are using an arrow function =>. You just need to change the type of the parameter:

    request.onerror = (e: ProgressEvent) => {
    
    }
    

    You don't really need to specify the type at all as it is inferred based on the type of onerror

    request.onerror = (e) => {
        e // is  ProgressEvent
    }
    

    If you use a regular function you can specify this

    request.onerror = function(this: XMLHttpRequest, e: ProgressEvent) {
         this // is XMLHttpRequest
    }
    

    Although you don't really need to as it will be implicitly typed based on the type of onerror

    request.onerror = function(e: ProgressEvent) {
         this // is still XMLHttpRequest
    }