Write a standard decorator for logging
Write a method decorator with the TC39 standard signature that logs arguments and results, no experimentalDecorators flag. TypeScript 5.0 or later.
Decorators wrap a method without editing its body. Since TypeScript 5.0 the standard form works without experimentalDecorators, and a logging decorator is the smallest useful one.
function logged<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const name = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`calling ${name} with`, args);
const result = target.call(this, ...args);
console.log(`${name} returned`, result);
return result;
};
}
class Calculator {
@logged
add(a: number, b: number): number {
return a + b;
}
}
console.log(new Calculator().add(2, 3));calling add with [ 2, 3 ]
add returned 5
5A standard method decorator receives the original function and a context object, and returns a replacement. The generics keep the types of this, the arguments and the result, so add is still typed (a: number, b: number) => number at the call site. See the TypeScript 5.0 notes on decorators.
Node.js does not run decorator syntax directly, so the file has to go through tsc or a bundler first. The old experimentalDecorators form has a different signature, and the two cannot be mixed in one project. For one-off wrapping, a plain higher-order function is simpler and needs no compiler support.