TypeScript 中的 noImplicitThis
说明 noImplicitThis 为什么会对隐式 any 的 this 表达式报错,以及它如何提前暴露 this 绑定上下文不明的问题。
#tech / dev
#resource / typescript
#type / concept
#status / growing
[!info] related notes
- 所属 MOC: TypeScript MOC
- 配置入口: tsconfig 使用详解
- 并列概念: TypeScript 中的 strict, TypeScript 中的 noImplicitAny, TypeScript 类型检查
TypeScript 中的 noImplicitThis
一句话定义
noImplicitThis 会对那些 this 实际类型推不出来、从而隐式落成 any 的场景报错。
核心机制 / 工作原理
官方文档定义是:
- Raise error on
thisexpressions with an impliedanytype
典型场景是:
class Rectangle {
width: number;
height: number;
getAreaFunction() {
return function () {
return this.width * this.height;
};
}
}
这里内部普通函数的 this 并不等于类实例本身,所以开启后 TypeScript 会指出:
thisimplicitly has typeany
最小例子 / 最小场景
{
"compilerOptions": {
"noImplicitThis": true
}
}
它最有价值的地方是:
- class 方法里返回内部函数
- 旧式对象方法写法
- 依赖
this语义的回调
边界与易混淆点
它不是“禁止使用 this”
它只是要求:
this的来源和类型必须足够明确
它和 noImplicitAny 很近,但关注对象不同
noImplicitAny更广泛noImplicitThis专门盯this表达式
它通常也跟着 strict 一起开
TSConfig 参考页当前写明:
trueifstrict;falseotherwise
参考信息
- TSConfig
noImplicitThis: https://www.typescriptlang.org/tsconfig/noImplicitThis.html - TSConfig Reference: https://www.typescriptlang.org/tsconfig/