TypeScript Decorators
A decorator is a function you attach to a class or class member with the @ syntax. It runs when the class is defined and can observe, wrap or replace what it decorates. Decorators are a neat way to add cross-cutting behaviour — logging, timing, validation, registration — without cluttering the method bodies themselves.
TypeScript 5.0 implemented the standard ECMAScript decorators proposal. That is what this lesson covers, and it works without any special compiler flag.
Note: Older code (Angular, NestJS, TypeORM) uses the earlier experimental decorators enabled with
"experimentalDecorators": true. Those have a different signature (target, propertyKey, descriptor) and support parameter decorators. Don't mix the two styles in one project.
A first method decorator
A standard method decorator receives two arguments: the original method and a context object describing it. If it returns a function, that function replaces the method.
function logged(original: Function, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
return function (this: unknown, ...args: unknown[]) {
console.log(`-> ${methodName}(${args.join(", ")})`);
const result = original.apply(this, args);
console.log(`<- ${methodName} returned ${result}`);
return result;
};
}
class Calculator {
@logged
add(a: number, b: number) {
return a + b;
}
}
new Calculator().add(2, 3);-> add(2, 3)
<- add returned 5
The context object tells the decorator what it is attached to:
| Property | Meaning |
|---|---|
kind |
"class", "method", "getter", "setter", "field" or "accessor" |
name |
the member's name (string or symbol) |
static / private |
whether the member is static / #private |
addInitializer(fn) |
run fn when the class (or each instance) is initialised |
metadata |
an object shared by all decorators of the class |
Typing decorators properly
The version above uses Function, which loses all type information. A generic signature keeps the method's this, arguments and return type intact, and lets TypeScript reject decorators placed on the wrong kind of member:
function timesTwo<This, Args extends unknown[]>(
original: (this: This, ...args: Args) => number,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => number>
) {
return function (this: This, ...args: Args): number {
return original.call(this, ...args) * 2;
};
}
class Shop {
@timesTwo
price(): number {
return 21;
}
@timesTwo
label(): string {
return "sale";
}
}main.ts(16,4): error TS1241: Unable to resolve signature of method decorator when called as an expression.
Argument of type '() => string' is not assignable to parameter of type '(this: Shop) => number'.
Type 'string' is not assignable to type 'number'.
main.ts(16,4): error TS1270: Decorator function return type '(this: Shop) => number' is not assignable to type 'void | (() => string)'.
Type '(this: Shop) => number' is not assignable to type '() => string'.
Type 'number' is not assignable to type 'string'.
timesTwo only makes sense on methods that return numbers, and the compiler enforces it. Remove @timesTwo from label and the code compiles:
function timesTwo<This, Args extends unknown[]>(
original: (this: This, ...args: Args) => number,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => number>
) {
return function (this: This, ...args: Args): number {
return original.call(this, ...args) * 2;
};
}
class Shop {
@timesTwo
price(): number {
return 21;
}
}
console.log(new Shop().price());42
Decorator factories
To pass options to a decorator, write a function that returns a decorator. This is called a decorator factory, and you call it in the @ expression:
function retry(times: number) {
return function <This, Args extends unknown[], R>(
original: (this: This, ...args: Args) => R,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>
) {
return function (this: This, ...args: Args): R {
for (let attempt = 1; ; attempt++) {
try {
return original.call(this, ...args);
} catch (err) {
console.log(`${String(context.name)} attempt ${attempt} failed: ${(err as Error).message}`);
if (attempt >= times) throw err;
}
}
};
};
}
class Uploader {
private calls = 0;
@retry(3)
send(file: string) {
this.calls++;
if (this.calls < 3) throw new Error("network busy");
return `${file} uploaded after ${this.calls} calls`;
}
}
console.log(new Uploader().send("report.pdf"));send attempt 1 failed: network busy
send attempt 2 failed: network busy
report.pdf uploaded after 3 calls
Class and field decorators
A class decorator receives the class itself. A common use is registering classes in a lookup table. A field decorator receives undefined as its first argument (the field has no value yet) and may return a function that transforms the initial value:
const registry = new Map<string, Function>();
function register(target: Function, context: ClassDecoratorContext) {
registry.set(String(context.name), target);
}
function upper(_value: undefined, context: ClassFieldDecoratorContext<unknown, string>) {
return (initial: string) => initial.toUpperCase();
}
@register
class Robot {
@upper model = "rx-2";
}
@register
class Drone {}
console.log([...registry.keys()]);
console.log(new Robot().model);[ 'Robot', 'Drone' ]
RX-2
Several decorators can be stacked on one member. They are evaluated top to bottom but applied bottom to top, so the decorator closest to the method wraps it first.
Tip: Keep decorators small and generic. If a decorator needs to know a lot about one specific class, a plain helper function is usually clearer.
Test yourself
What two arguments does a standard (TS 5) method decorator receive?
- target, propertyKey
- the method and a context object
- the class and its prototype
- the arguments and the return value
What is a decorator factory?
- A class that creates decorators via
new - A function that returns a decorator, used like
@retry(3) - A built-in TypeScript type
- A decorator applied to a constructor
Which compiler flag do TS 5 standard decorators need?
- experimentalDecorators
- emitDecoratorMetadata
- None
- decorators: true