Javascript TS2331和#x9';这';无法在模块或命名空间正文中引用

Javascript TS2331和#x9';这';无法在模块或命名空间正文中引用,javascript,typescript,interface,this,Javascript,Typescript,Interface,This,我试图创建一个接口,但在实现它的过程中出现了一个错误。 错误:TS2331“this”不能在模块或命名空间正文中引用。 module myInterface { interface IPerson { name: string; age: number; greet: () => void; myAge: () => void; } var person: IPerson = {

我试图创建一个接口,但在实现它的过程中出现了一个错误。 错误: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的另一个例子

更多
  • 向上读箭头

你的
greet
myAge
函数都是箭头函数,所以
这个
将不会是person对象。你知道,你可以避免在javascript中使用
这个
,而不是像TypeScript这样有争议的东西。)