Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

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.

logged.tsTypeScript
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));
Text
calling add with [ 2, 3 ]
add returned 5
5

A 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.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.