typescript - 为什么 `this` 在函数内部被键入为 `any`?

标签 typescript

如果我在模块中有一个函数,TypeScript 允许我执行类似 this.unexistingFunction(); 的操作(其中 unexistingFunction 没有'存在)。发生这种情况是因为 this 在函数内部具有类型 anỳ

这是为什么呢?在此上下文中,没有理由将 this 键入为 any,而且它很容易出错。例如,如果我不小心键入 this.myFunction(); 而不是 myFunction(); 来调用本地函数,编译器会让我这样做,即使 this.myFunction(); 显然不存在。

最佳答案

您可以启用 --noImplicitThis true 选项来限制 thisany 类型(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

Check this from Typescript Playground

关于typescript - 为什么 `this` 在函数内部被键入为 `any`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279435/

相关文章:

jquery - SPFx 不能使用 JQuery?

javascript - 识别带有一个异步函数调用的嵌套 FOR 循环和 IF 语句何时完成

android - NativeScript:扩充 tns-platform-declarations

typescript - 用于检查函数参数可分配性的自定义 TSLint 规则(无双方差)

javascript - 将反向属性和反向类选择器与现有选择器相结合

javascript - 如何将 Javascript 文件导入 Typescript

javascript - 无法使用 ngx translate/core - angular 2 typescript 获取文本的动态翻译

javascript - 在 li 的 ngFor 中,ngclass 应用于 li 标记的所有行我想应用一个特定行

typescript - 我可以将两种类型 <K, V> 转换为具有这些类型的单个字段的对象类型吗?

typescript - 为azure函数api( typescript )创建文档swagger