Open In App

How to Implement a TypeScript Decorator ?

Last Updated : 10 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, decorators are a feature that allows you to attach metadata to classes, methods, properties, or parameters concisely and expressively. TypeScript decorators are applied using the @decorator syntax. In this article, we are going to learn how to implement a typescript decorator.

How to enable TypeScript Decorators?

Using TypeScript Compiler CLI

To enable the support for decorators using the TypeScript Compiler CLI (tsc), you needed to pass an additional flag, that is.

tsc --experimentalDecorators

By manually changing the tsconfig.json

To enable decorator support in TypeScript, you need to set the experimentalDecorators option to true in your tsconfig.json file.

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

The “@” symbol in TypeScript is used to apply decorators. Decorators are a way to modify or observe the behavior of classes, methods, properties, or parameters at design time.

Example 1: In this TypeScript example, a class decorator named LogClass is defined. This decorator is then applied to the class ExampleClass using the @ syntax. The purpose of the decorator is to log a message when an instance of the decorated class is being created.

Javascript




// Class decorator
function LogClass(constructor: Function) {
    console.log("Logging the data");
}
 
@LogClass
class ExampleClass {
    constructor() {
        console.log("Instance of ExampleClass created.");
    }
}
 
const demoexample = new ExampleClass()


Output:

Logging the data 
Instance of ExampleClass created.

Example 2: In this TypeScript example, a class decorator named MonitorClass is defined. This decorator is applied to the class Vehicle using the @ syntax. The purpose of the decorator is to monitor and log a message when an instance of the decorated class is being created.

Javascript




// Class decorator
function MonitorClass(constructor: Function) {
    console.log(`Monitoring: ${constructor.name}`);
}
 
@MonitorClass
class Vehicle {
    constructor(public model: string) {
        console.log(`Creating a new ${model} vehicle.`);
    }
}
 
const car = new Vehicle('Sedan');


Output:

Monitoring: Vehicle 
Creating a new Sedan vehicle.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads