Runtime registration
Register classes in a framework or dependency-injection container during module initialization.
TypeScript · Decorator
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.
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.
@decoratorExpression
class ClassName { }| Name | Type | Description |
|---|---|---|
constructor | Function | The constructor of the class being decorated; it is the decorator's sole runtime argument. |
A replacement constructor function, if the decorator returns a value; otherwise the original class remains in use.
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); // replacementThe decorator returns a constructor, so that constructor replaces the original class at runtime.
Register classes in a framework or dependency-injection container during module initialization.
Attach or configure behavior shared by instances through the class definition.
Return a derived or alternative constructor to substitute the original implementation.
DecoratorexperimentalDecoratorsDecorators