TypeScript Decorators: Experimental and Stage 3
TypeScript decorators have existed in a state of flux for years. The original `experimentalDecorators` flag shipped in TypeScript 1.5, implementing a proposal that never made it through TC39....
Key Insights
- TypeScript supports two incompatible decorator systems: legacy experimental decorators and modern Stage 3 decorators, each requiring different compiler flags and offering distinct capabilities
- Stage 3 decorators introduce a context object with
addInitializerfor setup logic, auto-accessors for field decoration, and a fundamentally different execution model that breaks compatibility with legacy decorators - Migration from legacy to Stage 3 requires rewriting decorators to use the new signature, replacing metadata reflection with context metadata, and carefully testing decorator execution order changes
The Decorator Landscape
TypeScript decorators have existed in a state of flux for years. The original experimentalDecorators flag shipped in TypeScript 1.5, implementing a proposal that never made it through TC39. Meanwhile, the JavaScript community developed a completely different decorator specification that reached Stage 3 in 2022. TypeScript 5.0 finally implemented this modern standard, creating a critical fork in the road.
This isn’t a simple upgrade path. Legacy and Stage 3 decorators are fundamentally incompatible. They have different signatures, different execution semantics, and different capabilities. If you’re using Angular, NestJS, TypeORM, or any framework built on legacy decorators, you can’t simply flip a compiler flag. Understanding both systems is essential for modern TypeScript development.
Legacy Decorators (Experimental)
Legacy decorators require the experimentalDecorators compiler flag. They come in five types: class, method, accessor, property, and parameter decorators. Each receives different arguments based on what they decorate.
Here’s a class decorator that adds metadata:
function Entity(tableName: string) {
return function <T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
__tableName = tableName;
__isEntity = true;
};
};
}
@Entity('users')
class User {
name: string;
email: string;
}
Method decorators receive the target, property key, and property descriptor:
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with:`, args);
const result = originalMethod.apply(this, args);
console.log(`${propertyKey} returned:`, result);
return result;
};
return descriptor;
}
class Calculator {
@Log
add(a: number, b: number): number {
return a + b;
}
}
Property decorators are more limited—they receive only the target and property key:
function MinLength(length: number) {
return function(target: any, propertyKey: string) {
let value: string;
const getter = () => value;
const setter = (newVal: string) => {
if (newVal.length < length) {
throw new Error(`${propertyKey} must be at least ${length} characters`);
}
value = newVal;
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
};
}
class Account {
@MinLength(8)
password: string;
}
Parameter decorators are primarily for metadata:
function Inject(token: string) {
return function(target: any, propertyKey: string | symbol, parameterIndex: number) {
const existingParams = Reflect.getMetadata('inject:params', target, propertyKey) || [];
existingParams[parameterIndex] = token;
Reflect.defineMetadata('inject:params', existingParams, target, propertyKey);
};
}
class UserService {
constructor(@Inject('Database') db: any) {}
}
Decorator factories are functions that return decorators, enabling parameterization:
function Retry(attempts: number = 3) {
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function(...args: any[]) {
for (let i = 0; i < attempts; i++) {
try {
return await originalMethod.apply(this, args);
} catch (error) {
if (i === attempts - 1) throw error;
console.log(`Retry ${i + 1}/${attempts}`);
}
}
};
return descriptor;
};
}
Stage 3 Decorators (Modern Standard)
Stage 3 decorators use a completely different signature. Instead of multiple parameters, they receive the decorated value and a context object. No more experimentalDecorators—they work with the default TypeScript configuration (or explicitly setting "experimentalDecorators": false).
The context object provides metadata and hooks:
function logged<T extends (...args: any[]) => any>(
target: T,
context: ClassMethodDecoratorContext
) {
const methodName = String(context.name);
return function(this: any, ...args: any[]) {
console.log(`Calling ${methodName} with:`, args);
const result = target.apply(this, args);
console.log(`${methodName} returned:`, result);
return result;
};
}
class Calculator {
@logged
add(a: number, b: number): number {
return a + b;
}
}
The addInitializer method lets you run code during class or instance initialization:
function registerMethod(target: any, context: ClassMethodDecoratorContext) {
context.addInitializer(function() {
const registry = (this.constructor as any).__methodRegistry || [];
registry.push(context.name);
(this.constructor as any).__methodRegistry = registry;
});
return target;
}
class ApiController {
@registerMethod
getUsers() {}
@registerMethod
createUser() {}
}
Auto-accessors are a new feature for field decoration:
function tracked<T>(
target: ClassAccessorDecoratorTarget<any, T>,
context: ClassAccessorDecoratorContext
): ClassAccessorDecoratorResult<any, T> {
const { get, set } = target;
return {
get() {
console.log(`Getting ${String(context.name)}`);
return get.call(this);
},
set(value: T) {
console.log(`Setting ${String(context.name)} to:`, value);
set.call(this, value);
}
};
}
class State {
accessor @tracked count = 0;
}
Getter and setter decorators work similarly:
function validate(min: number, max: number) {
return function(target: any, context: ClassSetterDecoratorContext) {
return function(this: any, value: number) {
if (value < min || value > max) {
throw new Error(`Value must be between ${min} and ${max}`);
}
target.call(this, value);
};
};
}
class Temperature {
private _celsius: number = 0;
@validate(-273.15, 1000)
set celsius(value: number) {
this._celsius = value;
}
}
Key Differences and Migration
The differences between legacy and Stage 3 decorators are substantial. Here’s a side-by-side comparison:
// Legacy
function LegacyLog(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Called ${propertyKey}`);
return original.apply(this, args);
};
return descriptor;
}
// Stage 3
function Stage3Log(target: Function, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
return function(...args: any[]) {
console.log(`Called ${methodName}`);
return target.apply(this, args);
};
}
Metadata handling differs significantly. Legacy decorators used reflect-metadata:
// Legacy with reflect-metadata
import 'reflect-metadata';
function Type(type: any) {
return function(target: any, propertyKey: string) {
Reflect.defineMetadata('design:type', type, target, propertyKey);
};
}
Stage 3 uses context metadata:
// Stage 3 with context metadata
function Type(type: any) {
return function(target: any, context: ClassFieldDecoratorContext) {
context.metadata[`type:${String(context.name)}`] = type;
};
}
Migration helper for gradual transitions:
function createCompatibleDecorator(legacyFn: Function, stage3Fn: Function) {
return function(...args: any[]) {
// Detect which decorator system by argument types
if (args.length === 3 && typeof args[2] === 'object' && 'value' in args[2]) {
return legacyFn(...args); // Legacy: target, key, descriptor
} else if (args.length === 2 && typeof args[1] === 'object' && 'kind' in args[1]) {
return stage3Fn(...args); // Stage 3: target, context
}
throw new Error('Unrecognized decorator arguments');
};
}
Practical Use Cases
Dependency injection with Stage 3 decorators:
const container = new Map<string, any>();
function Injectable(token: string) {
return function<T extends { new(...args: any[]): {} }>(
target: T,
context: ClassDecoratorContext
) {
context.addInitializer(function() {
container.set(token, this);
});
return target;
};
}
function Inject(token: string) {
return function(target: undefined, context: ClassFieldDecoratorContext) {
return function(this: any) {
return container.get(token);
};
};
}
@Injectable('UserService')
class UserService {
getUser(id: string) { return { id, name: 'John' }; }
}
class UserController {
@Inject('UserService')
accessor userService!: UserService;
}
Runtime validation:
function Validate(schema: (value: any) => boolean) {
return function(target: any, context: ClassSetterDecoratorContext) {
return function(this: any, value: any) {
if (!schema(value)) {
throw new Error(`Validation failed for ${String(context.name)}`);
}
target.call(this, value);
};
};
}
class User {
private _email: string = '';
@Validate((v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v))
set email(value: string) {
this._email = value;
}
}
Memoization decorator:
function Memoize(target: any, context: ClassMethodDecoratorContext) {
const cache = new Map<string, any>();
return function(this: any, ...args: any[]) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = target.apply(this, args);
cache.set(key, result);
return result;
};
}
class Calculator {
@Memoize
fibonacci(n: number): number {
if (n <= 1) return n;
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}
Best Practices and Gotchas
Configure TypeScript correctly in tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": false,
"emitDecoratorMetadata": false
}
}
For legacy decorators:
{
"compilerOptions": {
"target": "ES2017",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Type-safe decorator implementation:
type Constructor<T = {}> = new (...args: any[]) => T;
function Timestamped<T extends Constructor>(
target: T,
context: ClassDecoratorContext
) {
return class extends target {
createdAt = new Date();
constructor(...args: any[]) {
super(...args);
console.log(`Instance created at ${this.createdAt}`);
}
};
}
Avoid performance anti-patterns:
// BAD: Creating new functions on every access
function Bad(target: any, context: ClassMethodDecoratorContext) {
return function(...args: any[]) {
const logger = new Logger(); // Created every call!
logger.log('Called');
return target.apply(this, args);
};
}
// GOOD: Reuse instances
const logger = new Logger();
function Good(target: any, context: ClassMethodDecoratorContext) {
return function(...args: any[]) {
logger.log('Called');
return target.apply(this, args);
};
}
Conclusion and Future Outlook
Use legacy decorators if you’re working with existing frameworks like Angular, NestJS, or TypeORM. These ecosystems have years of investment in the experimental decorator system and won’t migrate overnight.
Choose Stage 3 decorators for new projects without framework dependencies. They’re the JavaScript standard, offer better type safety, and provide more powerful initialization hooks through addInitializer.
The TypeScript team has committed to supporting both systems indefinitely. Framework migration will happen gradually over the next few years. Monitor your dependencies—libraries like class-validator and class-transformer are already planning Stage 3 versions.
The decorator story in TypeScript is finally stabilizing, but you need to understand both systems to navigate the transition period effectively. Choose based on your dependencies, not just the newer standard.