@decorator Decorators
Last updated: 2026-10-22
@decorator Decorators
A decorator is special syntax (@name) placed before classes, methods, properties or parameters: a wrapping function that attaches behavior (logging, validation, DI) to a class without touching its code. Decorators are still experimental in TypeScript and require experimentalDecorators in tsconfig; frameworks like NestJS and TypeORM lean on them heavily, making them essential reading for those codebases.
| Group | Engineering & Practice |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
// Class decorator: receives the constructor
function sealed(Ctor: Function): void {
Object.seal(Ctor);
Object.seal(Ctor.prototype);
}
// Method decorator: receives (prototype, method name, property descriptor)
function logged(target: object, key: string, desc: PropertyDescriptor): void {
const original = desc.value;
desc.value = function (...args: unknown[]) {
console.log("call", key, args);
return original.apply(this, args);
};
}
@sealed
class Calculator {
@logged
add(a: number, b: number) { return a + b; }
}
⚙️ Parameters
| ClassDecorator | Receives the class constructor; can mutate the class or return a replacement — used for whole-class constraints like @sealed |
|---|---|
| MethodDecorator | Runs once at class definition time; wraps the original by rewriting desc.value, or replaces the whole descriptor via the return value |
| experimentalDecorators | tsconfig flag; without it decorators are a compile error. The framework ecosystem (NestJS etc.) currently builds on this experimental version |
Returns:A class decorator may return a replacement constructor (or nothing, keeping the original); a method decorator may return a new property descriptor or undefined and act through side effects only.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
-> add(2, 3)
add = 5
-> mul(4, 5)
mul = 20
(Runtime output after transpilation; the method decorator wraps at class-definition time — each call logs "-> add(2, 3)" before returning the result)