← Back to TypeScript Course | Chapter 10: Decorators | Lesson 2 of 7

Class Decorators

A class decorator runs when a class is defined and receives the class constructor plus a ClassDecoratorContext. It can register the class, run static initialization logic, or return a compatible replacement class.

Basic Class Decorator

A class decorator is placed directly before a class declaration and can inspect or transform the class as a whole, receiving the class's constructor as its argument.

Example: Basic Class Decorator

typescript
function sealed(constructor: Function) {
  console.log("Sealing class", constructor.name);
}
@sealed
class Account {
  balance = 0;
}
new Account();

Class Initializers

Class decorators can call context.addInitializer to schedule additional logic to run right after the class has finished being defined, without having to modify the class body directly.

Example: Class Initializers

typescript
function withInit(target: any, context: ClassDecoratorContext) {
  context.addInitializer(function (this: any) {
    console.log("Initialized", this.constructor.name);
  });
}
@withInit
class Service {}
new Service();

Replacing a Class

A class decorator may return a new constructor compatible with the original class, effectively swapping in a modified or wrapped version of the class wherever it's used — a common pattern for adding cross-cutting behavior.

Example: Replacing a Class

typescript
function loggedClass<T extends { new (...args: any[]): {} }>(Base: T) {
  return class extends Base {
    constructor(...args: any[]) {
      super(...args);
      console.log("Created instance of", Base.name);
    }
  };
}
@loggedClass
class Widget {}
new Widget();

Class Decorator Factories

A decorator factory is a function that itself returns a class decorator, letting it capture configuration values from its own arguments so one factory can produce differently-configured decorators.

Example: Class Decorator Factories

typescript
function tag(name: string) {
  return function (target: Function) {
    console.log(`Tagging ${target.name} as ${name}`);
  };
}
@tag("service")
class UserService {}
new UserService();

Multiple Class Decorators

Several class decorators can be applied to the same class at once; when there are multiple, the decorator expressions are evaluated and applied in a specific, predictable order.

Example: Multiple Class Decorators

typescript
function first(target: Function) {
  console.log("first applied to", target.name);
}
function second(target: Function) {
  console.log("second applied to", target.name);
}
@first
@second
class Example {}
new Example();
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.