如何在 Typescript 中使用 XMLHttpRequest?

use*_*939 5 xmlhttprequest typescript

这对我来说是一个新情况,我使用 TypeScript 已经很长时间了,但在XMLHttpRequest.

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

我如何正确处理该错误响应?我上面的代码在编译过程中失败了:

错误 TS2322:类型(e: ErrorEvent) => void不可分配给类型(this: XMLHttpRequest, ev: ProgressEvent) => any

我没想到。

如果您将代码更改为

request.onerror = (this: XMLHttpRequest, ev: ProgressEvent) => {
};
Run Code Online (Sandbox Code Playgroud)

它不是有效的打字稿。即使是这样,this作为参数名称也是令人难以置信的混乱。

是否可以提供一个如何捕获 XMLHttpRequest 错误的示例?

Tit*_*mir 7

您无法指定的原因this是因为您使用的是箭头函数=>。您只需要更改参数的类型:

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

}
Run Code Online (Sandbox Code Playgroud)

您根本不需要指定类型,因为它是根据类型推断的 onerror

request.onerror = (e) => {
    e // is  ProgressEvent
}
Run Code Online (Sandbox Code Playgroud)

如果您使用常规函数,则可以指定 this

request.onerror = function(this: XMLHttpRequest, e: ProgressEvent) {
     this // is XMLHttpRequest
}
Run Code Online (Sandbox Code Playgroud)

虽然你真的不需要,因为它会根据类型隐式输入 onerror

request.onerror = function(e: ProgressEvent) {
     this // is still XMLHttpRequest
}
Run Code Online (Sandbox Code Playgroud)