简体   繁体   English

在这个打字稿片段中,`(this as any)` 是什么意思?

[英]what does `(this as any)` mean in this typescript snippet?

I meet this code and do not understand exactly what it does :我遇到了这段代码,但并不完全理解它的作用:

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);
  }

Can anyone explain what does this (this as any) statement do?任何人都可以解释这个(this as any)语句的作用是什么?

(this as any ) is just a Type Assertion that works on dev/compiling time and has no side effects on run time because it is purely a Typescript thing. (this as any)只是一个类型断言,它适用于开发/编译时并且对运行时没有副作用,因为它纯粹是一个 Typescript 的东西。 It can be useful if something related to this like this[whatever] which outputs a TS error because whatever is not defined inside the this TS type.如果事情有关它可以是有用的thisthis[whatever] ,其输出,因为TS误差whatever未在内部限定this TS类型。 So, this error can be suppressed with (this as any)[whatever]所以,这个错误可以被抑制(this as any)[whatever]

Also (this as any) is the equivalent to (<any> this)此外(this as any)等价于(<any> this)

Note to mention: --suppressImplicitAnyIndexErrors as a compiler option suppresses those kind of possible errors.请注意:-- --suppressImplicitAnyIndexErrors作为编译器选项可抑制那些可能的错误。

It can be actually written as其实可以写成

 (<any>this)[transport](item);

The type casting is exhibited in the above statement!上面的语句中展示了类型转换!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM