typescript `(this as any)` 在这个打字稿片段中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42551681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what does `(this as any)` mean in this typescript snippet?
提问by madjardi
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)语句的作用是什么?
采纳答案by Mouneer
(this as any )is just a Type Assertionthat 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]
(this as any )只是一个类型断言,它适用于开发/编译时并且对运行时没有副作用,因为它纯粹是一个 Typescript 的东西。它可以是有用的,如果相关的东西this
喜欢this[whatever]
,因为其输出TS错误whatever
未在内部限定this
TS类型。所以,这个错误可以被抑制(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 optionsuppresses those kind of possible errors.
请注意:--suppressImplicitAnyIndexErrors
作为编译器选项可以抑制那些可能的错误。
回答by arunprakashpj
It can be actually written as
其实可以写成
(<any>this)[transport](item);
The type casting is exhibited in the above statement!
上面的语句中展示了类型转换!