Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 731
Manos Serifios Avatar asked Jan 11 '18 22:01

Manos Serifios


People also ask

What is method decorator in TypeScript?

A Method Decorator is declared just before a method declaration. The decorator is applied to the Property Descriptor for the method, and can be used to observe, modify, or replace a method definition.

Can I use decorators in TypeScript?

In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.

What are method decorators in Angular?

In AngularJS, decorators are functions that allow a service, directive, or filter to be modified before it is used. There are four main types of angular decorators: Class decorators, such as @Component and @NgModule. Property decorators for properties inside classes, such as @Input and @Output.

Are TypeScript decorators experimental?

Since decorators are an experimental feature, they are disabled by default. You must enable them by either enabling it in the tsconfig. json or passing it to the TypeScript compiler ( tsc ).


1 Answers

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.

like image 182
Lajos Gallay Avatar answered Sep 19 '22 11:09

Lajos Gallay