TypeScript Reference ยท Classes, Enums and Decorators
TypeScript decorator context object
Reference for the second argument of standard TypeScript decorators: kind, name, static, private, access, addInitializer and metadata, per decorator type.
Every standard decorator receives a context object as its last argument. It describes what is being decorated and gives you hooks that a plain function value cannot offer. The object's type depends on the member kind: ClassDecoratorContext, ClassMethodDecoratorContext, ClassGetterDecoratorContext, ClassSetterDecoratorContext, ClassFieldDecoratorContext or ClassAccessorDecoratorContext.
All of them share a kind string that works as a discriminant, so one decorator function can accept several kinds and narrow on it.
function inspect(_value: unknown, context: DecoratorContext): void { console.log(context.kind, String(context.name)); }
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
| Property | Applies to | Description |
|---|---|---|
kind |
all | "class", "method", "getter", "setter", "field" or "accessor". |
name |
all | The member name (string or symbol), or the class name (possibly undefined). |
static |
members | true for static members. |
private |
members | true for #private members. |
access |
members | Object with has(obj) and get(obj) (plus set(obj, value) for writable kinds). |
addInitializer(fn) |
all | Registers a callback run when the instance (or class, for static and class decorators) is set up. |
metadata |
all | A shared object per class for passing data between decorators (needs Symbol.metadata). |
Edge cases: access.get on a #private member only works from inside the decorator machinery, which is the point: it grants access without exposing the name.
Usage notes
DecoratorContextis a union of all six context types; narrow withkind.- For methods,
addInitializercallbacks run at the start of construction (before field initializers), so you can bind methods there. For fields they run after that field is initialized. metadatais a plain object whose prototype is the parent class's metadata, so child classes inherit what the parent recorded.- At run time
Symbol.metadatamay not exist yet; the second example installs it. Without it,context.metadataisundefined. - Decorator context is read-only information plus these hooks; it cannot change the class shape that the type checker sees.