capypad
0 day streak
typescript / expert
Snippet

Contextual Metadata with Stage 3 Decorators

Stage 3 decorators provide a type-safe way to wrap class members. Unlike older experimental decorators, these use a structured 'context' object containing the member name, private/static status, and other metadata without requiring 'reflect-metadata'.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
function loggedMethod<This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
) {
const methodName = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`Calling ${methodName}`);
return target.call(this, ...args);
};
}
Breakdown
1
ClassMethodDecoratorContext<This, ...>
The standardized context object provided by the runtime during decoration.
2
context.name
Accesses the name of the method being decorated directly from the context.
3
return function (this: This, ...args: Args)
Returns a replacement function that maintains the original 'this' context and arguments.