如果我在模块中有一个函数,TypeScript
允许我执行类似 this.unexistingFunction();
的操作(其中 unexistingFunction
没有'存在)。发生这种情况是因为 this
在函数内部具有类型 anỳ
。
这是为什么呢?在此上下文中,没有理由将 this
键入为 any,而且它很容易出错。例如,如果我不小心键入 this.myFunction();
而不是 myFunction();
来调用本地函数,编译器会让我这样做,即使 this.myFunction();
显然不存在。
最佳答案
您可以启用 --noImplicitThis true
选项来限制 this
为 any
类型(this:any
won '不允许)
例子:
class Rectangle {
//private w: number; //uncomment this line
//private h: number; //uncomment this line
constructor(w, h) {
this.w = w;
this.h = h;
}
getAreaFunction() {
return () => {
return this.w * this.h;
};
}
}
let rectangle = new Rectangle(2, 5);
let areaFunction = rectangle.getAreaFunction();
let area = areaFunction();
console.log(area);
注意:编译 tsc --noImplicitThis
关于typescript - 为什么 `this` 在函数内部被键入为 `any`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279435/