TypeScript Reference ยท Classes, Enums and Decorators
TypeScript class decorators
Reference for standard TypeScript class decorators: the (value, context) signature, returning a replacement class, registering classes with addInitializer, and typing.
A class decorator is a function applied to a whole class by writing @name above the class keyword. It receives the class constructor and a ClassDecoratorContext. It can return nothing (and just observe or register the class) or return a new class that replaces the original.
These are the standard decorators from TypeScript 5.0 on, the same design that is moving into JavaScript. They are different from the older experimentalDecorators, which pass different arguments.
function sealed(target: Function, context: ClassDecoratorContext): void { Object.seal(target); Object.seal(target.prototype); } @sealed class Point {}
Try it
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.
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.
Syntax
type ClassDecorator<C extends abstract new (...args: any) => any> = ( value: C, context: ClassDecoratorContext<C>, ) => C | void;
| Name | Description |
|---|---|
value |
The class being decorated (its constructor function). |
context |
ClassDecoratorContext with kind: "class", name, addInitializer and metadata. |
Returns: void to keep the class, or a constructor that is compatible with the original to replace it.
Edge cases: the class name is undefined for an anonymous default export. Returning a non-function is a run-time error.
Usage notes
- The decorator runs once, when the class definition is evaluated, not on each instantiation.
- A replacement class changes the runtime identity of the binding, but the compile-time type is still the original class. A decorator cannot add properties that TypeScript will see; access them through a cast or a separate interface, as the second example does.
- Callbacks passed to
context.addInitializerrun after the class is defined and its static fields are initialized, which is the right moment to freeze or register it. - Several decorators are evaluated top to bottom and applied bottom to top.
- Decorators are not erased: they need the compiler (or another transpiler) to rewrite them, so Node's type stripping rejects files that use them.