TypeScript-DOM-lib-generator
TypeScript-DOM-lib-generator copied to clipboard
Improve XMLHttpRequest status usage inside onload event
Hi I am trying to use the status property inside the onload event of the XMLHttpRequest object but it is throwing a type error on it. There are different approaches to workaround it today:
Forcing with as XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.onload = function (event: ProgressEvent) {
const target = event.target as XMLHttpRequest;
console.dir(target.status);
console.dir(target.response);
}
Or using closure
const xhr = new XMLHttpRequest();
xhr.onload = function (event: ProgressEvent) {
console.dir(xhr.status);
console.dir(xhr.response);
}
But what I was expecting to work is this:
xhr.onload = function (event: ProgressEvent<XMLHttpRequest>) {
const target = event.target;
console.dir(target.status);
console.dir(target.response);
}
It makes more clear that the event target type is going to be a type of XMLHttpRequest.
Just an explanation: Without strictFunctionTypes in your tsconfig your code works out of the box.
https://www.typescriptlang.org/play?strictFunctionTypes=false&jsx=0&module=0#code/MYewdgzgLgBAHgCwE4wLwzAUwO4wBoCyAMgBJRQAOASpgI4Cum0AFAJQDcAUIkgHQCGAE0EBRAG6YwUIgEtokzEmYByADYghygDQwAZvTDAoM8DGaYJUgFwwACkhABzJEwjjJUADyFS5anUZoAD5WGABvThgomFBIWCh+JEdMWHQLD14EpJSuaJjwCBBVTF5BGSUs5KheaH4oeggOSOjYwuLS8uZKlN4XCAoCzCaAX1ZObmRecHUhND0DIxMwM3TrOwdnV3cpb2IyShoGJigQ8Oao1vjEqrnV6u6oXJaCopKyiuue2vrGp4uX9rvLqfap9AaQIZcYZAA
The error is:
Type '(this: XMLHttpRequest, event: ProgressEvent<XMLHttpRequest>) => void' is not assignable to type '(this: XMLHttpRequest, ev: ProgressEvent<EventTarget>) => any'.
Types of parameters 'event' and 'ev' are incompatible.
Type 'ProgressEvent<EventTarget>' is not assignable to type 'ProgressEvent<XMLHttpRequest>'.
Type 'EventTarget' is missing the following properties from type 'XMLHttpRequest': onreadystatechange, readyState, response, responseText, and 27 more.