Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 96 ยท Modern Features

Decorators

Learn standard TypeScript decorators - method, field, accessor and class decorators, context objects, logging, memoize, validation and legacy decorators.

A decorator is a function you attach to a class or one of its members with @name. When the class is defined, the decorator receives the thing it decorates and can observe it, replace it or register it somewhere. That lets you write cross-cutting behavior once (logging, caching, validation, binding, dependency registration) and apply it with a single line wherever you need it:

TypeScript
class ReportService {
  @logged
  @memoize
  build(month: string): Report { /* ... */ }
}

TypeScript has supported decorators for a long time, but there are two different systems. Since TypeScript 5.0, plain @decorator syntax means the standard decorators from the TC39 proposal that is becoming part of JavaScript itself. The older "experimental" decorators, still used by Angular and NestJS, need the experimentalDecorators compiler flag and behave differently. This lesson teaches the standard ones, which our editor uses, and shows how to recognize the legacy style at the end.

Your first decorator: wrapping a method

A method decorator is a function that receives two arguments: the original method and a context object describing where it was applied. Whatever function it returns replaces the method. Here is a decorator that logs each call, typed so that it works on any method:

TypeScript A logging method decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The three type parameters are what make the decorator reusable. This captures the class instance type, Args the parameter list and Return the return type, so the wrapper has exactly the same signature as the original. Callers still see divide(a: number, b: number): number; nothing about the method's type changes. Inside the wrapper, target.call(this, ...args) forwards the real this, which is why this.precision still works.

The generics lesson explains this style of type parameter. If generics feel heavy, you can start with a looser signature like (target: Function, context: ClassMethodDecoratorContext), but you lose the checks shown next.

Decorators are type-checked

Because decorators are ordinary typed functions, TypeScript checks that each decorator fits what it's applied to. A decorator whose target parameter expects a method that returns a number can't decorate a method that returns a string. This example fails on purpose:

TypeScript A decorator applied to the wrong method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler reports an error on the second @nonNegative, starting with main.ts(18,4): error TS1241: Unable to resolve signature of method decorator when called as an expression., followed by the detail Argument of type '() => string' is not assignable to parameter of type '(this: Account) => number'. and a second error, TS1270, about the decorator's return type. Delete the decorator on label() and the program prints 0: the withdrawal would leave -15, and the decorator clamps it.

The context object

Every decorator receives a context object. Its type depends on what you decorate, and its kind property tells you which one you have:

Decorated thing kind Context type Receives May return
Class 'class' ClassDecoratorContext the class a replacement class
Method 'method' ClassMethodDecoratorContext the method a replacement method
Getter / setter 'getter' / 'setter' ClassGetterDecoratorContext / ClassSetterDecoratorContext the accessor function a replacement function
Field 'field' ClassFieldDecoratorContext undefined an initializer function
Auto-accessor (accessor x) 'accessor' ClassAccessorDecoratorContext { get, set } { get, set, init }

The member contexts share useful properties: name (the member's name, a string or symbol, or the #name text for private members), static and private (booleans), access (functions to read or write the member on a given object), addInitializer(fn) (run code when each instance is constructed, or when the class is defined for static members) and metadata.

context.metadata is an object shared by all decorators on one class, meant for frameworks that record information (like validation rules) to read later through MyClass[Symbol.metadata]. TypeScript emits it only when the runtime defines Symbol.metadata, which Node 24 doesn't yet, so in our editor context.metadata is undefined. Libraries that rely on it ship a one-line polyfill that defines Symbol.metadata before any class is declared.

Decorator factories: decorators with arguments

@logged takes no options. To configure a decorator, like @retry(3) or @memoize({ ttl: 60 }), write a factory: a function that takes the options and returns the actual decorator. Here is a caching decorator and a timing decorator with a label, both factories:

TypeScript Decorator factories: memoize and counted

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Only two [slow] lines appear for three calls: 7919 is computed once and then served from the cache. The order of decorators matters here. Decorator expressions are evaluated top to bottom, but decorators are applied bottom to top, the one closest to the method first. So @counted wraps the original method, and @memoize wraps the counted version; a cache hit returns before the counting wrapper runs. Swap the two lines and every call would be counted.

The cache lives in a WeakMap keyed by instance, so each Primes object has its own cache and an instance that is no longer used can be garbage-collected along with it. (Note the This extends object constraint, needed because WeakMap keys must be objects.)

Field and accessor decorators

A field decorator can't wrap anything, because a field has no value until an instance is constructed. Instead, it receives undefined and may return an initializer: a function that receives each field's initial value and returns the value to store. That's enough for normalizing values, but not for intercepting later assignments.

For that, decorate an auto-accessor. The accessor keyword (see access modifiers) turns a field into a private storage slot plus a getter and setter, and an accessor decorator can replace the getter, the setter and the initializer:

TypeScript Field and accessor decorators for validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is "Kitchen" 30, then 75, then the error message volume must be between 0 and 100, got 140, and finally 75 again because the invalid assignment was rejected. The returned ClassAccessorDecoratorResult only overrides init and set; the omitted get keeps its default behavior. Notice that the decorator's types tie it to number accessors, so @range on a string accessor would be a compile error.

Class decorators and addInitializer

A class decorator receives the class itself (its constructor). A common use is registering classes in a lookup table, for plugins, commands or serializers, so you don't need a central list that everyone has to edit. Member decorators can also call context.addInitializer() to run code for every new instance; the classic example is @bound, which fixes this for methods passed around as callbacks:

TypeScript Registering classes and binding methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Class decorators run when the class definition is evaluated, so both registered ... lines print before anything else. The type parameter C extends new () => Shape means @shape only accepts classes whose instances are Shapes with a no-argument constructor; applying it to a class without an area() method is a compile error.

Without @bound, calling the detached describe() would crash with TypeError: Cannot read properties of undefined (reading 'label'), the lost this problem. The initializer runs at the start of each construction and stores a bound copy of the method on the instance. (An arrow-function field, describe = () => ..., solves the same problem without a decorator; @bound keeps the method on the prototype for subclasses to override.)

A class decorator may also return a new class, usually a subclass that adds behavior, and that class replaces the original. TypeScript checks that the returned class is compatible with the decorated one, but it can't change the class's type: methods added by a decorator are invisible to the type checker. If a decorator needs to add members that callers use, a mixin function is the typed alternative.

Legacy experimental decorators

You'll meet the older decorator system in Angular, NestJS, TypeORM, MobX (older versions), InversifyJS and many existing codebases. It's enabled in tsconfig.json:

JSON
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

The syntax looks the same, but the functions have different signatures, so a decorator written for one system doesn't work in the other:

TypeScript
// Legacy (experimentalDecorators): target, property key and descriptor
function legacyLogged(target: object, key: string, descriptor: PropertyDescriptor): void {
  const original = descriptor.value;
  descriptor.value = function (this: unknown, ...args: unknown[]) {
    console.log(`calling ${key}`);
    return original.apply(this, args);
  };
}

// Legacy-only: parameter decorators, used for dependency injection
@Injectable()
class OrdersController {
  constructor(@Inject(ORDERS_REPO) private readonly orders: OrdersRepository) {}
}

The main differences to keep in mind:

Standard decorators (default) Legacy (experimentalDecorators)
Arguments (value, context) (target, key, descriptor) for methods
Parameter decorators Not supported Supported (@Inject(...) in constructors)
emitDecoratorMetadata Not supported; use context.metadata Emits design-time types for DI frameworks
Auto-accessors (accessor) Supported Not supported
Status Being standardized in JavaScript TypeScript-only, will not be standardized

Use whatever your framework requires: Angular and NestJS projects keep experimentalDecorators on, and that's fine. For your own decorators in new code, use the standard system shown above. One runtime caveat: standard decorators are JavaScript syntax, so erasableSyntaxOnly allows them, but JavaScript engines don't run them natively yet (Node 24 included). Today they work because TypeScript, or a bundler like esbuild or Babel, compiles them into ordinary function calls. That's also why Node's built-in type stripping can't run a file that uses decorators.

Decorators are powerful but hide behavior: a reader of @memoize fetchRate() has to know what memoize does to understand the method. Keep each decorator small, name it after its effect, and prefer a plain function call (const fetchRate = memoize(rawFetchRate)) when there's no class involved.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What two arguments does a standard method decorator receive?

    Standard decorators receive (value, context). For a method, value is the method itself and context is a ClassMethodDecoratorContext with name, kind, static, private, access, addInitializer and metadata.
  2. 2. A method has @a on the first line and @b on the line below it. Which decorator wraps the original method directly?

    Decorator expressions are evaluated top to bottom, but applied bottom to top. The decorator closest to the method wraps it first, and the outer one wraps the result.
  3. 3. Why does validating every assignment need an accessor decorator instead of a field decorator?

    A field decorator returns an initializer that runs once per instance. An accessor decorator can replace the setter, so it sees every later assignment.
  4. 4. What is context.metadata in our editor (Node 24, no polyfill)?

    TypeScript's emitted code creates the metadata object only when Symbol.metadata exists. Frameworks that use metadata include a small polyfill for it.
  5. 5. Which feature exists only in the legacy experimentalDecorators system?

    Standard decorators do not support decorating parameters. Dependency-injection frameworks like Angular and NestJS rely on legacy parameter decorators and emitDecoratorMetadata.

Summary

  • A decorator is a function applied with @name to a class, method, getter, setter, field or accessor; it runs when the class is defined.
  • Standard decorators (the default since TypeScript 5.0) receive (value, context). The context has kind, name, static, private, access, addInitializer and metadata.
  • Method decorators return a replacement function. Type them with This, Args and Return parameters so the method's signature is preserved and misuse is a compile error.
  • Factories (@memoize({ maxEntries: 100 })) take options and return the decorator. Several decorators are evaluated top to bottom and applied bottom to top.
  • Field decorators return an initializer; accessor decorators can replace get, set and init, so they can validate every assignment.
  • Class decorators receive the class (registries, replacement subclasses); addInitializer runs per-instance setup such as @bound.
  • Angular and NestJS use legacy experimentalDecorators with different signatures and parameter decorators. Engines don't run decorators natively yet, so a compile step (TypeScript, esbuild, Babel) is still required.

Next: using Declarations and Explicit Resource Management