Open In App

TypeScript Decorators

TypeScript Decorators are a new and special way of declaring the classes, methods, parameters, and properties. The decorators are defined using the @expression syntax, where the expression will be a function that is to be invoked at the runtime with the information of the decorated declaration.

Syntax:

// A decorator with the name @dempDecorator
// can be declared as follows.
function demoDecorator(){
// Decorator statements
}

The decorators can be implemented by editing some properties in the tsconfig.json file. You need to set the value of the experimentalDecorators to true inside the compiler options.



{
'compilerOptions': {
'target': ES5,
'experimentalDecorators': true
}
}

You can also set the experimentalDecorators to true or enable it by using the below command.

tsc --target ES5 --experimentalDecorators

TypeScript Decorators

Example 1: The below example will explain how you can implement the decorators practically.






// Decorator method
function decoratorMethod(realMethod: any, _ctx: any) {
    function replacedDecoratorMethod(this: any,
        ...args: any[]) {
        console.log(`Hi, ${realMethod.name}
      method starts executing here.`);
        const res = realMethod.call(this, ...args);
        console.log(`The ${realMethod.name}
       method stops executing here.`);
        return res;
    }
 
    return replacedDecoratorMethod;
}
 
// Implementing class for decorator method
class User {
    constructor(private name: string,
        private desc: string) { }
 
    @decoratorMethod
    welcome() {
        console.log(`Hello, Welcome to
       ${this.name}.`);
    }
 
    @decoratorMethod
    description() {
        console.log(`It is "${this.desc}".`);
    }
}
 
const user = new User("GeeksforGeeks",
    "A Computer Science portal for all geeks");
user.welcome();
user.description();

Output:

Hi, welcome method starts executing here.
Hello, Welcome to GeeksforGeeks
The welcome method stops executing here
Hi, description method starts executing here.
It is "A Computer Science portal for all geeks".
The description method stops executing here.

Example 2: The below example will illustrate how you can implement the decorators practically.




function ClassDecorator(constructorDecorator: Function) {
  constructorDecorator.prototype.runs = 26000;
}
 
@ClassDecorator
class Cricketer {
  constructor(public c_name: string) {}
}
 
const crktr = new Cricketer('Virat Kohli');
console.log(crktr.c_name, crktr.runs);

Output:

Virat Kohli,  26000 

Article Tags :