Standard decorators in TypeScript
Write a standard method decorator in TypeScript, compile it to JavaScript and run it in Node.
You want to log every call to a method without editing the method. You find a decorator example, paste it above add, and the compiler answers The runtime will invoke the decorator with 2 arguments, but the decorator expects 3. That example uses the legacy decorator signature.
TypeScript 5.0 supports the standard decorators from the TC39 proposal, and they work with no compiler flag. The decorator receives the original method as value and its metadata as context. You return a function to replace the method.
function logCalls<This, Args extends unknown[], Return>(
value: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const name = String(context.name)
console.log(`decorating ${name}`)
return function (this: This, ...args: Args): Return {
console.log(`calling ${name}(${args.join(', ')})`)
const result = value.call(this, ...args)
console.log(`${name} returned ${result}`)
return result
}
}
class Calculator {
@logCalls
add(a: number, b: number) {
return a + b
}
}
const calc = new Calculator()
calc.add(2, 3)
calc.add(4, 5)The generics let value keep the real parameter and return types of add, so the replacement has the same shape. context.name is the method's name, "add", which saves you from hard-coding it.
The body of logCalls runs once, when the class is defined. The function it returns runs on every call.
Compile and run
Node 22's TypeScript loader cannot transform decorators. Save the example as index.ts and compile it with TypeScript 5.0 or newer before running it. Use this tsconfig.json to target ES2022.
{
"compilerOptions": {
"target": "ES2022",
"strict": true,
"outDir": "dist"
},
"files": ["index.ts"]
}$ pnpm exec tsc -p .
$ node dist/index.js
decorating add
calling add(2, 3)
add returned 5
calling add(4, 5)
add returned 9With TypeScript installed in the project, the command emits dist/index.js. Each call to add prints a line before and after the original method runs.
The other signature
The older decorators from experimentalDecorators take three arguments, (target, key, descriptor), and you mutate the descriptor. Without the flag, such a decorator fails with the error in the first paragraph. With the flag on, my standard decorator failed the other way: Unable to resolve signature of method decorator.
If a library asks you to turn the flag on, you are in the old mode and the standard signature will not work there. If you write your own decorators, leave the flag off.
emitDecoratorMetadata belongs to the old mode as well. With that flag alone, tsc stops with Option 'emitDecoratorMetadata' cannot be specified without specifying option 'experimentalDecorators'.