代码之家  ›  专栏  ›  技术社区  ›  user1059939

如何在Typescript中使用XMLHttpRequest?

  •  2
  • user1059939  · 技术社区  · 6 年前

    这对我来说是一个新的情况,我已经用了很长一段时间,但是我一直在努力 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错误的示例?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Titian Cernicova-Dragomir    6 年前

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

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

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

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

    如果使用正则函数,可以指定

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

    尽管您不需要,因为它将根据 误差

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