Decorators are a feature of TypeScript that provides syntax for annotating and performing metaprogramming on classes, methods, accessors, properties, or parameters. They are a mechanism used to modify or wrap existing classes or their members.
In TypeScript, decorators are a special type of declaration that can be attached to class declarations, methods, accessors, properties, or parameters. Decorators use the @expression syntax, where expression must evaluate to a function that is called at runtime with the decorated declaration information passed as arguments.
For example, a simple decorator @sealed can be used to seal a class, preventing other code from inheriting from it:
typescriptfunction sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype); } @sealed class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } }
In this example, the sealed decorator prevents other code from inheriting from the Greeter class. When attempting to inherit from this class, JavaScript will throw an error.
Decorators can also be used to monitor, modify, or replace the definition of class members. For example, you can use decorators to log the invocation details of a method:
typescriptfunction log(target: any, propertyName: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { console.log(`Calling "${propertyName}" with`, args); let result = originalMethod.apply(this, args); console.log(`Result: ${result}`); return result; } return descriptor; } class Calculator { @log add(x: number, y: number) { return x + y; } } const calculator = new Calculator(); calculator.add(2, 3);
In this example, the log decorator modifies the add method, causing each call to add to log detailed invocation information and results to the console.
Overall, decorators are a powerful syntax feature provided by TypeScript for enhancing and extending the behavior of classes and their members, making the code more flexible and expressive.