TypeScript 78 ๐ท Decorators โ Stage 3 Standard
The previous chapter covered the legacy experimental decorators โ the version that required a compiler flag, relied on reflect-metadata, and powered frameworks like NestJS and TypeORM. This chapter covers the Stage 3 decorators, which TypeScript 5.0 shipped as the default. The new design is a near-rewrite of the legacy model: decorators receive a context object describing what they decorate, they return values explicitly rather than mutating the prototype, and they integrate with the type system far better. Legacy decorators continue to work under the experimentalDecorators flag, but the ecosystem โ Lit, MobX, Effect, MikroORM โ has converged on the standard. This chapter covers the new API shape, the context object’s properties, the accessor keyword, the differences from the legacy system, and the migration path.
Key point: Stage 3 decorators receive two arguments: the value being decorated, and a context object. The context object’s kind property identifies what is being decorated ("class", "method", "field", "accessor", "getter", "setter"), and the name, static, private, and addInitializer properties provide additional metadata . Method and accessor decorators can return a replacement function. Field decorators receive undefined and can return an initializer function. The accessor keyword creates an auto-accessor with a getter/setter pair that decorators can wrap . Stage 3 decorators do not support parameter decorators and do not emit reflect-metadata, which is why frameworks like NestJS and TypeORM still require the legacy system .
Why Stage 3 decorators exist
The legacy decorators were never standardized. They modeled an older Stage 2 proposal that was ultimately abandoned, and they required a compiler flag that marked them as experimental . The Stage 3 proposal is the version that TC39 actually approved, and it addresses the legacy system’s problems.
The typing problem. The legacy decorator signatures use any for the target and string for the property key. There is no type safety at the decorator boundary. A method decorator receives (target: any, propertyKey: string, descriptor: PropertyDescriptor), and the compiler cannot verify that the decorator is being applied to the correct kind of element . The Stage 3 context object is fully typed per decorator kind, and the kind property lets the decorator assert what it is decorating.
The mutation problem. Legacy decorators mutate the PropertyDescriptor in place. The Stage 3 decorators return values explicitly: a method decorator returns a replacement function, a field decorator returns an initializer, and a class decorator returns a replacement class . This makes the decorator’s effect visible in its return type rather than hidden in a mutation.
The metadata problem. The legacy emitDecoratorMetadata flag emits runtime type metadata using reflect-metadata, which powers dependency injection in NestJS and Angular. The Stage 3 proposal does not include metadata emission, and the feature was removed entirely . This is the primary reason the framework ecosystem has not migrated.
Why the accessor keyword matters. Stage 3 introduces the accessor keyword for auto-accessors โ properties with a built-in getter/setter pair that decorators can wrap. MobX requires @observable accessor instead of @observable because the standard decorators need the accessor to intercept reads and writes .
Enabling Stage 3 decorators
Stage 3 decorators are the default in TypeScript 5.0 and later. No compiler flag is required. The only requirement is that experimentalDecorators is not enabled.
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": false
}
}
If experimentalDecorators is true, TypeScript uses the legacy implementation and ignores the Stage 3 semantics. The two modes are mutually exclusive . The emitDecoratorMetadata flag is also incompatible with Stage 3 decorators and must be disabled .
Why the target matters. Stage 3 decorators use Symbol.metadata for the metadata storage, which requires a modern target. ES2022 or later is recommended .
The context object
The context object is the core of the Stage 3 API. It tells the decorator what it is decorating and provides hooks for initialization.
function logged<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const methodName = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`Calling ${methodName}`);
return target.call(this, ...args);
};
}
The context.kind is "method", and context.name is the method name . The decorator returns a replacement function, and that replacement is what runs when the method is called.
The context properties:
| Property | Purpose |
|---|---|
kind | The decorator kind ("class", "method", "field", "accessor", "getter", "setter") |
name | The element’s name (string or symbol) |
static | Whether the element is static |
private | Whether the element is private |
addInitializer | Register initialization logic |
The addInitializer method lets a decorator run code when the class is defined or when an instance is created. It is the standard replacement for the Reflect.defineMetadata pattern .
Method decorators
A method decorator receives the method function and the context. It can return a replacement function.
function log(target: Function, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
return function (this: any, ...args: any[]) {
console.log(`โ ${methodName}(${args.join(", ")})`);
const result = target.apply(this, args);
console.log(`โ ${methodName}`);
return result;
};
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
The @log decorator wraps the method, logging before and after. The return value replaces the original method .
Why the return value is the mechanism. Unlike the legacy system, which mutated the descriptor, the Stage 3 method decorator returns a new function. If the decorator returns nothing, the original method is used. This makes the decorator’s effect explicit in its return type .
Why the this typing matters. The generic signature <This, Args extends unknown[], Return> lets the decorator preserve the method’s this type, argument types, and return type. The legacy system lost all of this to any .
Field decorators
A field decorator receives undefined as its first argument and the context as its second. It can return an initializer function that runs when an instance is created.
function format(formatString: string) {
return function (target: undefined, context: ClassFieldDecoratorContext) {
return function (this: any, value: any) {
return formatString.replace("%s", value);
};
};
}
class Greeter {
@format("Hello, %s")
greeting = "World";
}
The field decorator returns an initializer that transforms the value. When an instance is created, the initializer runs and the transformed value is assigned .
Why undefined is the first argument. Fields do not exist on the prototype at class definition time. The decorator cannot inspect the field’s value because there is no value yet. The return value is an initializer function that receives the initial value and returns the transformed value .
Why the initializer pattern matters for ORMs. MikroORM’s Stage 3 decorators return initializers that preserve hydrated values. Without this, the class field definition would overwrite the value the ORM assigned .
The accessor keyword
The accessor keyword creates an auto-accessor โ a property with a getter and setter that decorators can wrap. It is the Stage 3 replacement for legacy property decorators that needed to intercept reads and writes.
class Todo {
@observable accessor title = "";
@observable accessor finished = false;
}
MobX requires the accessor keyword for @observable because the decorator needs to intercept property access. Without accessor, the decorator cannot wrap the property .
Why accessor exists. A plain field is just a value. An accessor has a getter and setter, which means a decorator can return a new getter/setter pair. This is how reactivity, validation, and serialization work in the Stage 3 world .
Why the accessor keyword is not the same as a manual getter/setter. The compiler generates the backing storage and the getter/setter pair. The decorator receives { get, set } and can return a replacement. This is more efficient than a manual getter/setter and gives the decorator a clean interface to work with .
Class decorators
A class decorator receives the class constructor and the context. It can return a replacement class.
function register(target: Function, context: ClassDecoratorContext) {
const className = String(context.name);
console.log(`Registering ${className}`);
return target;
}
@register
class Service {}
The class decorator runs after all method and field decorators have been applied . It can modify the class, wrap it, or return a new class.
Why the order matters. Method and field decorators run first, then the class decorator. The class decorator sees the fully decorated class .
The comparison with legacy
| Aspect | Legacy | Stage 3 |
|---|---|---|
| Flag | experimentalDecorators: true | None |
| Signature | (target, key, descriptor) | (value, context) |
| Typing | any | Typed per kind |
| Mutation | In-place descriptor | Return value |
| Parameter decorators | Supported | Not supported |
| Metadata emission | Supported | Not supported |
accessor keyword | Not available | Required for field interception |
Why the frameworks have not migrated. NestJS and TypeORM rely on parameter decorators for dependency injection and on emitDecoratorMetadata for type reflection. Neither feature exists in Stage 3. The frameworks must wait for future proposals or restructure their DI systems .
Why MikroORM supports both. MikroORM offers @mikro-orm/decorators/legacy and @mikro-orm/decorators/es. The ES decorators use ts-morph to read type information from source files, replacing the reflect-metadata approach .
Complete Example Session
// ============================================
// PART 1: THE TSCONFIG
// ============================================
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": false
}
}
// ============================================
// PART 2: THE METHOD DECORATOR
// ============================================
function log<This, Args extends unknown[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
const methodName = String(context.name);
return function (this: This, ...args: Args): Return {
console.log(`Calling ${methodName}`);
return target.call(this, ...args);
};
}
class Calculator {
@log
add(a: number, b: number): number {
return a + b;
}
}
// ============================================
// PART 3: THE FIELD DECORATOR
// ============================================
function format(formatString: string) {
return function (target: undefined, context: ClassFieldDecoratorContext) {
return function (this: any, value: any) {
return formatString.replace("%s", value);
};
};
}
class Greeter {
@format("Hello, %s")
greeting = "World";
}
// ============================================
// PART 4: THE ACCESSOR
// ============================================
class Todo {
@observable accessor title = "";
@observable accessor finished = false;
}
// ============================================
// PART 5: THE CLASS DECORATOR
// ============================================
function register(target: Function, context: ClassDecoratorContext) {
console.log(`Registering ${String(context.name)}`);
return target;
}
@register
class Service {}
// ============================================
// PART 6: THE CONTEXT OBJECT
// ============================================
// Inside any decorator:
// context.kind โ "method" | "field" | "class" | "accessor" | ...
// context.name โ the element's name
// context.static โ true/false
// context.private โ true/false
// context.addInitializer โ register init logic
// ============================================
// PART 7: THE EVALUATION ORDER
// ============================================
// @first
// @second
// method() {}
//
// 1. first evaluated
// 2. second evaluated
// 3. second called
// 4. first called
// 5. class decorator called last
// ============================================
// PART 8: THE MODERN FRAMEWORKS
// ============================================
// MobX 6.11+:
class Todo {
@observable accessor title = "";
@action toggle() { this.finished = !this.finished; }
}
// MikroORM (ES decorators):
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/es';
@Entity()
class User {
@PrimaryKey() id!: number;
@Property() fullName!: string;
}
// ============================================
// PART 9: THE LEGACY MIGRATION
// ============================================
// Legacy:
@observable title = "";
// Constructor: makeObservable(this);
// Stage 3:
@observable accessor title = "";
// No makeObservable call.
// ============================================
// PART 10: WHAT NOT TO DO
// ============================================
// Don't enable experimentalDecorators with Stage 3
// The two are mutually exclusive.
// Don't use parameter decorators with Stage 3
// They are not supported.
// Don't expect emitDecoratorMetadata
// It is not compatible.
// Don't use Stage 3 with NestJS/TypeORM yet
// They require the legacy system.
// Don't forget the accessor keyword for field interception
// @observable title = ""; // โ
The ten parts cover the tsconfig, the method decorator, the field decorator, the accessor, the class decorator, the context object, the evaluation order, the modern frameworks, the legacy migration, and the anti-patterns.
Quick Reference
The Context Object
| Property | Type | Purpose |
|---|---|---|
kind | String literal | What is being decorated |
name | string | symbol | The element’s name |
static | boolean | Static element |
private | boolean | Private element |
addInitializer | Method | Register init logic |
The Decorator Kinds
| Kind | First Argument | Return Value |
|---|---|---|
"method" | The method function | Replacement function |
"field" | undefined | Initializer function |
"accessor" | { get, set } | Replacement { get, set, init } |
"getter" | The getter function | Replacement function |
"setter" | The setter function | Replacement function |
"class" | The constructor | Replacement class |
The Compiler Options
| Option | Stage 3 | Legacy |
|---|---|---|
experimentalDecorators | false | true |
emitDecoratorMetadata | Not compatible | Optional |
target | ES2022+ | Any |
The Comparison
| Feature | Stage 3 | Legacy |
|---|---|---|
| Flag required | No | Yes |
| Typed context | Yes | No |
| Return value | Explicit | Mutation |
| Parameter decorators | No | Yes |
| Metadata emission | No | Yes |
accessor keyword | Yes | No |
The Framework Support
| Framework | Stage 3 | Legacy |
|---|---|---|
| MobX 6.11+ | Yes (accessor) | Yes |
| MikroORM v7 | Yes (/es) | Yes (/legacy) |
| Lit | Yes | Deprecated |
| NestJS | No | Yes |
| TypeORM | No | Yes |
Best Practices
โ Do This:
// Disable experimentalDecorators
{
"experimentalDecorators": false
} // โ
// Use the typed context object
function log(target: Function, context: ClassMethodDecoratorContext) { ... } // โ
// Return a replacement function
return function (this: This, ...args: Args): Return { ... }; // โ
// Use the accessor keyword for interception
@observable accessor title = ""; // โ
// Use addInitializer for registration
context.addInitializer(() => { ... }); // โ
// Use the ES decorators for modern frameworks
import { Entity } from '@mikro-orm/decorators/es'; // โ
โ Don’t Do This:
// Don't enable experimentalDecorators with Stage 3
{
"experimentalDecorators": true
} // โ ๏ธ
// Don't use parameter decorators
constructor(@inject("DB") db: any) {} // โ ๏ธ
// Don't expect reflect-metadata
Reflect.getMetadata("design:paramtypes", Service); // โ ๏ธ
// Don't use Stage 3 with NestJS/TypeORM
@Injectable() // NestJS requires legacy // โ ๏ธ
// Don't forget the accessor keyword
@observable title = ""; // โ the decorator cannot intercept // โ ๏ธ
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
experimentalDecorators: true | Legacy mode | Set false |
| Parameter decorator | Compile error | Not supported |
Missing accessor | No interception | Add accessor |
emitDecoratorMetadata | Incompatible | Remove it |
| Framework mismatch | Runtime error | Check framework support |
| Field decorator return | No effect | Return initializer |
Real-World Examples
1. The method decorator
function log(target: Function, context: ClassMethodDecoratorContext) { ... }
2. The field decorator
function format(fmt: string) {
return function (target: undefined, context: ClassFieldDecoratorContext) {
return function (value: any) { return fmt.replace("%s", value); };
};
}
3. The accessor
@observable accessor title = "";
4. The class decorator
function register(target: Function, context: ClassDecoratorContext) { return target; }
5. The context object
context.kind; context.name; context.static; context.private;
6. The addInitializer
context.addInitializer(() => console.log("initialized"));
7. The MobX usage
class Todo {
@observable accessor title = "";
@action toggle() { ... }
}
8. The MikroORM ES decorators
import { Entity, PrimaryKey, Property } from '@mikro-orm/decorators/es';
9. The tsconfig
{ "experimentalDecorators": false, "target": "ES2022" }
10. The legacy migration
// Before: @observable title = "";
// After: @observable accessor title = "";
Visual: The Stage 3 Decorator API
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ @decorator โ
โ method() {} โ
โ โ
โ The decorator receives: โ
โ (value, context) โ
โ โ โ โ
โ โ โโโ the context object โ
โ โโโ the method function โ
โ โ
โ The decorator returns: โ
โ a replacement function โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: The Context Object
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ context = { โ
โ kind: "method", โ
โ name: "greet", โ
โ static: false, โ
โ private: false, โ
โ addInitializer: (fn) => { ... } โ
โ } โ
โ โ
โ The kind identifies the element. โ
โ The name is the element's name. โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: The accessor Keyword
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ @observable accessor title = ""; โ
โ โ โ โ
โ โ โโโ the auto-accessor โ
โ โโโ the decorator wraps get/set โ
โ โ
โ WITHOUT accessor: โ
โ @observable title = ""; โ
โ โ the decorator cannot intercept โ
โ โ
โ WITH accessor: โ
โ @observable accessor title = ""; โ
โ โ the decorator wraps the getter/setter โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: The Legacy vs Stage 3
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LEGACY โ
โ @log โ
โ method() {} โ
โ โ (target, key, descriptor) โ
โ โ mutates the descriptor โ
โ โ requires experimentalDecorators โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ STAGE 3 โ
โ @log โ
โ method() {} โ
โ โ (value, context) โ
โ โ returns a replacement โ
โ โ no flag required โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Visual: The Framework Support
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STAGE 3 READY โ
โ MobX 6.11+ (with accessor) โ
โ MikroORM v7 (via /es) โ
โ Lit โ
โ Effect โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ LEGACY ONLY โ
โ NestJS (parameter decorators) โ
โ TypeORM (metadata reflection) โ
โ Angular (pre-v16) โ
โ โ
โ The migration waits on parameter decorators โ
โ and metadata proposals. โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Default | TypeScript 5.0+ |
| Flag | None (experimentalDecorators: false) |
| Signature | (value, context) |
| Context kinds | "class", "method", "field", "accessor", "getter", "setter" |
| Return value | Explicit replacement |
accessor keyword | For field interception |
| Parameter decorators | Not supported |
| Metadata emission | Not supported |
| Target | ES2022+ |
Key takeaways:
- Stage 3 decorators are the default in TypeScript 5.0+ โ no compiler flag is required, and
experimentalDecoratorsmust befalse - The signature is
(value, context)โ the context object’skindproperty identifies what is being decorated, andname,static,private, andaddInitializerprovide additional metadata - Method decorators return a replacement function โ the returned value is what runs when the method is called, replacing the legacy mutation pattern
- Field decorators return an initializer โ the decorator receives
undefinedand returns a function that transforms the initial value - The
accessorkeyword creates auto-accessors โ it is required for field interception, and MobX uses@observable accessorinstead of@observable - Class decorators run last โ method and field decorators run first, then the class decorator sees the fully decorated class
- Parameter decorators and metadata emission are not supported โ this is why NestJS and TypeORM still require the legacy system
- The typed context object replaces the
anysignature โ the generic<This, Args, Return>preserves the method’s types, and thekindproperty lets decorators assert what they decorate - The modern frameworks have migrated โ MobX 6.11+, MikroORM v7, Lit, and Effect support Stage 3; the backend frameworks wait on future proposals
- The migration from legacy is mechanical but not automatic โ disable
experimentalDecorators, replace@observablewith@observable accessor, and removemakeObservablecalls
Remember: Stage 3 decorators are the standardized version that TypeScript 5.0 shipped as the default. They replace the any-typed legacy signatures with a typed context object, replace in-place mutation with explicit return values, and add the accessor keyword for field interception. The tradeoff is the loss of parameter decorators and metadata emission, which keeps the backend frameworks on the legacy system. For frontend libraries and modern applications, Stage 3 is the present and the future.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!