DecoratorsIntermediate
1Question 1 of 1
typescriptHow do Decorators work in TypeScript (Stage 3 vs experimental)?
Explanation & Concept
Decorators are functions applied to classes, methods, accessors, or properties to observe or modify their behavior. TypeScript supports ECMAScript Stage 3 standard decorators.
Code Example
typescript
function logged(target: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
return function (this: any, ...args: any[]) {
console.log(`Entering method: ${methodName}`);
const result = target.apply(this, args);
console.log(`Exiting method: ${methodName}`);
return result;
};
}
class PaymentProcessor {
@logged
charge(amount: number) {
return `Charged $${amount}`;
}
}How It Works & Key Takeaways
The `@logged` decorator wraps the `charge` method transparently, providing aspect-oriented logging without modifying the core business logic.
Mock Test · 1 Questions · Optional
Ready for Modules & Namespaces?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions