admin管理员组

文章数量:1178553

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?

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?

Share Improve this question edited Dec 30, 2019 at 19:15 Sinan 11.6k7 gold badges38 silver badges48 bronze badges asked Mar 2, 2017 at 9:37 madjardimadjardi 5,9292 gold badges38 silver badges40 bronze badges 4
  • 6 this as any is a cast. It casts the this to the any type (which also removes most compile time type checks) – UnholySheep Commented Mar 2, 2017 at 9:46
  • 2 It not casting @UnholySheep, this is assertion. Casting works in run time but assertion working on dev/compiling and has no side effects because it is a purely Typescript thing. – Mouneer Commented Mar 2, 2017 at 9:59
  • 1 @Mouneer Microsoft themselves sometimes call it a cast (as in the release notes of TypeScript 1.6) so that's where my confusion of terms stemmed from – UnholySheep Commented Mar 2, 2017 at 10:02
  • No wonder, I feel they always intend to confuse us :D – Mouneer Commented Mar 2, 2017 at 10:06
Add a comment  | 

2 Answers 2

Reset to default 29

(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. 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. So, this error can be suppressed with (this as any)[whatever]

Also (this as any) is the equivalent to (<any> this)

Note to mention: --suppressImplicitAnyIndexErrors as a compiler option suppresses those kind of possible errors.

It can be actually written as

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

The type casting is exhibited in the above statement!

本文标签: javascriptwhat does (this as any) mean in this typescript snippetStack Overflow