javascript - TS2331 'this' 无法在模块或命名空间主体中引用

标签 javascript typescript interface this

我正在尝试创建一个接口(interface),但在实现它时出现错误。 错误:无法在模块或命名空间主体中引用 TS2331“this”。

module myInterface {
    interface IPerson {
        name: string;
        age: number;
        greet: () => void;
        myAge: () => void;
    }

    var person: IPerson = {
        name: "Gautam",
        age: 1,
        greet: () => {
            console.log("Hey, " + this.name);
        },
        myAge: () => { console.log(this.age); }
    }

    var greetMe = person.greet();
    var agee = person.myAge();
}  

最佳答案

来自您的代码:

{
        name: "Gautam",
        age: 1,
        greet: () => {
            console.log("Hey, " + this.name);
        },

}

this.name 引用 name: "Gautam" 因为箭头函数如何与 this 一起工作>。这只是 TypeScript 的另一种情况 preventing bad JavaScript .

更多

关于javascript - TS2331 'this' 无法在模块或命名空间主体中引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877695/

相关文章:

typescript - 记录 TypeScript 代码的工具和指南?

java - 接口(interface)常量有什么用?

delphi - 抽象与接口(interface) - 在 Delphi 中分离定义和实现

class - 接口(interface)和类中的函数重载 - 怎么做?

javascript - 如何在 android/三星手机的 html 文本输入字段中停止自动大写?

javascript - Electron.js错误: require is not defined

javascript - 使用 JavaScript : How can a variable be added to a string containing quotation marks?

java - Webdriver 确实存在时没有这样的元素,我已经等待了足够长的时间

typescript - 类型 'string | number | null | undefined' 不可分配给类型 'null'

typescript - JSDoc 中的 "T extends Component"