Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

TypeScript · Decorator

ClassDecorator

A class decorator is a function applied to a class declaration at runtime. It receives the class constructor and can observe, modify, or replace the class by returning another constructor.

How it works

A class decorator is written immediately before a class and receives that class's constructor when the program runs. It may inspect or modify the class, or return another constructor; returning a value replaces the decorated class. Class decorators are not allowed in declaration files or other ambient contexts.

Syntax

@decoratorExpression
class ClassName { }

Parameters

NameTypeDescription
constructorFunctionThe constructor of the class being decorated; it is the decorator's sole runtime argument.

Returns

A replacement constructor function, if the decorator returns a value; otherwise the original class remains in use.

Key points

  • Place the decorator directly before the class declaration it decorates.
  • The decorator works with the class constructor rather than an instance.
  • Use a class decorator to inspect, alter, or substitute a class.
  • The decorator expression is evaluated and invoked while the program runs.
  • A legacy class decorator receives exactly the decorated class constructor.
  • In decorator evaluation order, class decorators run after the listed member and constructor decorators.

Common mistakes

  • Do not apply a class decorator to a declaration file or an ambient class such as a declare class.
  • Returning a constructor changes which class definition the decorated binding uses.

Example: Replacing a class with a decorator

function ReplaceWith<T extends new (...args: any[]) => any>(replacement: T) {
  return (_target: Function): T => replacement;
}

class Replacement {
  value = "replacement";
}

@ReplaceWith(Replacement)
class Original {
  value = "original";
}

console.log(new Original().value); // replacement

The decorator returns a constructor, so that constructor replaces the original class at runtime.

When to use it

Runtime registration

Register classes in a framework or dependency-injection container during module initialization.

Class customization

Attach or configure behavior shared by instances through the class definition.

Constructor replacement

Return a derived or alternative constructor to substitute the original implementation.

  • Decorator
  • experimentalDecorators
  • Decorators

Source: Documentation - Decorators - TypeScript. Checked 2026-10-15.