Rjk Rjk - 3 months ago 14
TypeScript Question

Typescript: Access other functions/properties of a class inside a decorator declaration

How can a decorator function inside a class object access a property inside that object. In the below imaginary example

this.name
is not returning the expected name "JohnDoe", its always empty.

class First {
name:string
constructor(name:string) {
this.name = name
}

nameProperty(target: any, key: string) {
...
console.log(this.name); //<--- this is always empty. was expecting "JohnDoe"
...
}
}

let f = First("JohnDoe")
class Second {
@f.nameProperty
dummyName:string

}

Answer

You are loosing this. Try capture it with arrow function like this:

class First {
   name:string
   constructor(name:string) {
       this.name = name
   }

    nameProperty() 
    {
        return (target: any, key: string) => 
        {
            console.log(this.name);
        }
    }
}

let f = new First("JohnDoe");
class Second {
    @f.nameProperty()
    dummyName:string

}