打字稿.是什么意思:(这和任何一样)

mad*_*rdi 14 javascript typescript

我遇到这个代码,并不完全明白它的作用:

public uploadItem(value:FileItem):void {
    let index = this.getIndexOfItem(value);
    let item = this.queue[index];
    let transport = this.options.isHTML5 ? '_xhrTransport' : '_iframeTransport';
    item._prepareToUploading();
    if (this.isUploading) {
      return;
    }
    this.isUploading = true;
    (this as any)[transport](item);
  }
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这个 (这个任何)声明是做什么的吗?

Mou*_*eer 14

(这与任何一样)只是一个类型断言,它适用于开发/编译时间,并且对运行时没有副作用,因为它纯粹是一个Typescript的东西.它可以是有用的,如果相关的东西,this喜欢this[whatever]它输出一个错误,因为这个错误可以被抑制whatever

this相当于(this as any)[whatever]

需要注意的是: (this as any)作为编译器选项可以抑制那些可能的错误.

  • @ BorisD.Teoharov,“任意”类型是使用现有JavaScript的强大方法,可让您在编译期间逐渐选择加入和选择退出类型检查。例如,((<any> this).myProperty)`,其中“ this”可以是“ window”对象或任何其他没有类型定义的第三方库。 (2认同)

aru*_*hpj 5

其实可以写成

 (<any>this)[transport](item);
Run Code Online (Sandbox Code Playgroud)

上面的语句中展示了类型转换!