TypeScript 中的 noImplicitThis

说明 noImplicitThis 为什么会对隐式 any 的 this 表达式报错,以及它如何提前暴露 this 绑定上下文不明的问题。

#tech / dev #resource / typescript #type / concept #status / growing

[!info] related notes

TypeScript 中的 noImplicitThis

一句话定义

noImplicitThis 会对那些 this 实际类型推不出来、从而隐式落成 any 的场景报错。

核心机制 / 工作原理

官方文档定义是:

  • Raise error on this expressions with an implied any type

典型场景是:

class Rectangle {
  width: number;
  height: number;

  getAreaFunction() {
    return function () {
      return this.width * this.height;
    };
  }
}

这里内部普通函数的 this 并不等于类实例本身,所以开启后 TypeScript 会指出:

  • this implicitly has type any

最小例子 / 最小场景

{
  "compilerOptions": {
    "noImplicitThis": true
  }
}

它最有价值的地方是:

  • class 方法里返回内部函数
  • 旧式对象方法写法
  • 依赖 this 语义的回调

边界与易混淆点

它不是“禁止使用 this”

它只是要求:

  • this 的来源和类型必须足够明确

它和 noImplicitAny 很近,但关注对象不同

  • noImplicitAny 更广泛
  • noImplicitThis 专门盯 this 表达式

它通常也跟着 strict 一起开

TSConfig 参考页当前写明:

  • true if strict; false otherwise

参考信息

创建于 2026/5/15 更新于 2026/5/27