Decorators are elegant tools in TypeScript that let us modify class behavior at runtime. You and I can use them to add logging, validation, or automatically bind methods without writing boilerplate code. Think of decorators as special decorators that enhance classes, methods, and properties with additional functionality.
Class decorators wrap our entire class definition, allowing you and I to add cross-cutting concerns like validation or dependency injection. Method decorators work on individual class methods, perfect for timing function execution or adding authentication checks.
When you and I use decorators, we keep our code clean and maintainable. We reduce repetitive code and create more expressive APIs that clearly communicate the purpose and behavior of our TypeScript classes.
Class Decorator - Logging
You and I can use class decorators to add logging functionality to our classes. This decorator wraps the original constructor to log when instances are created, helping us track object creation throughout our application.
function LogClass(constructor: Function) {
console.log(`Creating ${constructor.name}`);
}
@LogClass
class User {
name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Alice");
Try it Yourself โ