What are decorators in TypeScript?
Answer
Decorators are special functions that modify the behavior of classes, methods, or properties. They are often used in frameworks like Angular.
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Method ${propertyKey} called with args:`, args);
return original.apply(this, args);
};
}
class Example {
@Log
greet(name: string) {
console.log(`Hello, ${name}!`);
}
}
const ex = new Example();
ex.greet("Alice");