TypeScript Master (50 Qs)•Part 2: Advanced Type System & Metaprogramming (Mid-Level)
How do ECMAScript Stage 3 Decorators work in TypeScript 5.x?
mid LevelCode ExampleTypeScript
In Simple Words:
TypeScript 5.0 adopted the official ECMAScript standard Decorators (replacing the legacy experimentalDecorators flag).
Decorators are functions applied to classes, methods, accessors, and fields to wrap or replace them:
typescript
function logged(target: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
return function (this: any, ...args: any[]) {
console.log(`Calling ${methodName} with args:`, args);
return target.apply(this, args);
};
}
class Calculator {
@logged
add(a: number, b: number) { return a + b; }
}