what does `(this as any)` mean in this typescript snippet?
Asked Answered
T

2

31

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?

Toque answered 2/3, 2017 at 9:37 Comment(4)
this as any is a cast. It casts the this to the any type (which also removes most compile time type checks)Shoemake
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.Lorenlorena
@Lorenlorena 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 fromShoemake
No wonder, I feel they always intend to confuse us :DLorenlorena
L
28

(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.

Lorenlorena answered 2/3, 2017 at 9:48 Comment(2)
What is the reason to explicitly assert (<any> this)? It looks like it is unnecessary.Cymene
@BorisD.Teoharov , The 'any' type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. For example, (<any> this).myProperty) where this can be the window object or any other thirdparty library with no type definitions.Lorenlorena
T
5

It can be actually written as

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

The type casting is exhibited in the above statement!

Tetracycline answered 2/3, 2017 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.