Class Decorators
In this page:
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
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
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
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
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
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: