gpt4 book ai didi

typescript - 我如何在 Typescript 中使用 XMLHttpRequest?

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:27 26 4
gpt4 key购买 nike

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

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

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

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

我没想到。

如果你把代码改成

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

它不是有效的 typescript 。即使是这样,this 作为参数名称也令人难以置信的困惑。

能否提供一个示例来说明如何捕获 XMLHttpRequest 错误?

最佳答案

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

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

}

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

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

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

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

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

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

关于typescript - 我如何在 Typescript 中使用 XMLHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51760227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com