Why decorators in typescript ?
TypeScript decorators are a special kind of declaration that can be attached to class declarations, methods, accessors, properties, or parameters. They are functions that are prefixed with the
@ symbol and are called at runtime with information about the decorated declaration.Purpose of Decorators:
-
Decorators can add metadata or annotations to classes and their members, providing information that can be consumed by other parts of the application or frameworks.
They allow for the modification or extension of the behavior of classes or their members at design time, without directly altering the original code. This is a form of meta-programming.
Decorators facilitate AOP by enabling the injection of cross-cutting concerns (like logging, validation, or authentication) into various parts of an application in a declarative manner.
They promote cleaner, more organized, and reusable code by encapsulating common functionalities that can be applied across multiple classes or members.
Types of Decorators:
TypeScript supports several types of decorators, each applied to a specific declaration type:
Class Decorators: Applied to a class declaration.
Method Decorators: Applied to a method within a class.
Accessor Decorators: Applied to a getter or setter (accessor) within a class.
Property Decorators: Applied to a property within a class.
Parameter Decorators: Applied to parameters of a method or constructor (supported in older decorator syntax, not in the current Stage 3 ECMAScript proposal).
Enabling Decorators:
To use decorators, they must be enabled in your TypeScript configuration. For the older, experimental Stage 2 decorators, you would set
experimentalDecorators to true in your tsconfig.json file:{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
For the newer Stage 3 decorators (introduced in TypeScript 5.0),
experimentalDecorators should be set to false (which is the default).Decorator Factories:
Decorators can also be created using decorator factories, which are functions that return the actual decorator function. This allows for customization and parameterization of decorators.
Example of a Class Decorator:
function Logger(constructor: Function) {
console.log('Logging...');
console.log(constructor);
}
@Logger
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User('Alice');
In this example, the
Logger decorator is applied to the User class, causing the Logger function to execute when the User class is defined, even before any instance is created.