打字稿:Type assertion as any,这是什么意思?

Typescript: Type assertion as any, what does this mean?

我想了解一段代码是如何工作的。我以前见过类型断言,但出于某种原因我无法解决这个问题。

(this.whatever as any).something([]);

更大的代码部分:

    resetThis(): void {
    if (this.whatever) {
        (this.whatever as any).something([]);
    }
}

尝试运行这个块时我得到错误:this.whatever.someting is not a function

您的代码等同于此 JavaScript 代码:

this.whatever.something([]);

当你在 TypeScript 中说 as any 时,你是在告诉编译器忽略前面表达式的前一个类型,而是将其视为 any 类型。所以在你的情况下,你告诉编译器 this.whatever 是类型 any.

TypeScript 中的 any 类型基本上是表示 "we don't know anything about what this variable really is, so let me do whatever I want with it" 的类型。 TypeScript 手册将其描述为 "opting out of typechecking".

假设 this.whatever 的类型为 IMyType

与:

IMyType {
  prop1: string;
  prop2: string;
}

所以如果你调用this.whatever.something([]),编译器会尖叫。因为something([])函数没有定义在IMyType.

使用as any 将告诉编译器对于该特定语句,它应该将this.whatever 视为any 类型。这意味着它可以有任何 属性 或它想要的方法。