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

GroupEngineering & Practice
KindSyntax
Strict modeNot 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

ClassDecoratorReceives the class constructor; can mutate the class or return a replacement — used for whole-class constraints like @sealed
MethodDecoratorRuns once at class definition time; wraps the original by rewriting desc.value, or replaces the whole descriptor via the return value
experimentalDecoratorstsconfig 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)

💡 Notes

ℹ️ Info Decorators run at class-definition time, not call time: the decorator function executes once when the class is evaluated, swapping desc.value for the wrapped version; every later call goes through the wrapper.
💡 Tip To parameterize a decorator use a factory: @log("debug") is a function returning a decorator — outer call takes config, inner takes (target, key, desc). NestJS's @Injectable() with parentheses is exactly this.
⚠️ Note Experimental and standard signatures are incompatible: since TS 5 you can drop experimentalDecorators and use standard ES decorators, where the method decorator receives a context object instead of (target, key, desc). Check which version is in play before reading legacy code or frameworks.
More cases coming soon.

📚 Related tutorials

❓ FAQ

Q How are decorators different from ordinary higher-order functions?
A At heart both wrap functions. The difference is placement: decorators sit above the decorated member and the compiler wires them up, keeping the class body clean; higher-order functions must be applied explicitly where created. Decorators read as tags and suit cross-cutting concerns.
Q How does @Injectable() in NestJS work?
A @Injectable() is a decorator factory; the returned class decorator attaches metadata marking the class as instantiable by the DI container. When building a Controller, the container reads constructor parameter metadata and resolves dependencies automatically — the decorator only registers information, injection happens in the container.
Q Should a new project use experimental or standard decorators?
A Follow your framework: with NestJS/TypeORM ecosystems keep experimentalDecorators (they rely on the old semantics); for your own code prefer standard decorators (TS 5+ default) — standardized in ES with no experimental baggage. The two styles cannot be mixed.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏