【问题标题】:what does `(this as any)` mean in this typescript snippet?`(this as any)` 在这个打字稿片段中是什么意思?
【发布时间】:2017-07-21 22:59:41
【问题描述】:

我遇到了这段代码,但不明白它的作用:

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

谁能解释一下这个(this as any)语句的作用是什么?

【问题讨论】:

  • this as any 是一个演员表。它将this 转换为any 类型(这也删除了大多数编译时类型检查)
  • 它没有投射@UnholySheep,这是断言。强制转换在运行时工作,但断言在开发/编译上工作并且没有副作用,因为它是一个纯粹的 Typescript 东西。
  • @Mouneer 微软自己有时称其为演员表(如release notes of TypeScript 1.6),所以这就是我对术语的混淆产生的原因
  • 难怪,我觉得他们总是想迷惑我们:D

标签: javascript typescript


【解决方案1】:

(this as any) 只是一个 Type Assertion,适用于开发/编译时间,并且对运行时间没有副作用,因为它纯粹是 Typescript 的东西.如果与this 相关的内容(例如this[whatever])输出TS 错误,则它可能很有用,因为whatever 未在this TS 类型中定义。所以,这个错误可以用(this as any)[whatever]来抑制

还有(this as any)等价于(<any> this)

请注意:--suppressImplicitAnyIndexErrors 作为compiler option 会抑制此类可能出现的错误。

【讨论】:

  • 明确断言(<any> this)的原因是什么?看起来没有必要。
  • @BorisD.Teoharov ,'any' 类型是使用现有 JavaScript 的一种强大方式,允许您在编译期间逐渐选择加入和退出类型检查。例如,(<any> this).myProperty) 其中this 可以是window 对象或任何其他没有类型定义的第三方库。
【解决方案2】:

其实可以写成

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

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

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 2021-04-24
    • 2018-10-29
    相关资源
    最近更新 更多