Manos Serifios
Manos Serifios

Reputation: 577

Typescript Method Decorator

I have this code

function changeFunc() {
    return function(target: any, title: string, descriptor: PropertyDescriptor) {

        descriptor.value = function () {
            console.log(this.name);
        };

        return descriptor;

    }
}


class Man {
    name: string = "asdsds";

    constructor(name: string) {
        this.name = name;
    }

    @changeFunc()
    getName() {
        console.log("Hello");
    }

}


var man = new Man('Manos Serifios');
man.getName();  

In other words i try (with the decorator) to change the method

getName() {  
    console.log("Hello");  
}  

with this

function () {
    console.log(this.name);
}

but this.name evaluated as undefined.

If i console log the "this" it seems that is the right(instance man).

Upvotes: 7

Views: 3682

Answers (3)

Ace
Ace

Reputation: 1146

@hackerman's answer worked for me, as it seems to just be a typing issue. An alternative solution would be to actively define the type of this for that function:

descriptor.value = function (this: Man) {
  console.log(this.name);
};

Upvotes: 0

hackerman
hackerman

Reputation: 31

You can do a little Hack. Replace your code

descriptor.value = function () {
  console.log(this.name);
};

with this nice trick:

descriptor.value = function () {
  // Hack 
  const self = this as Man;
  console.log(self.name);
};

Upvotes: 3

Lajos Gallay
Lajos Gallay

Reputation: 1317

You don't have the context of a specific object instance inside the decorator method. The parameters are the following (from https://www.typescriptlang.org/docs/handbook/decorators.html):

Either the constructor function of the class for a static member, or the prototype of the class for an instance member.

The name of the member.

The Property Descriptor for the member.

Upvotes: 7

Related Questions