lesson depth
Mastery
not started · 0%

TypeScript Decorators & Metadata

Stage 3 TC39 decorators, legacy experimental decorators, and reflect-metadata reflection.

Freshness: current14 min readSoftware and Web Engineering

Key Learning Outcomes

  • Author Stage 3 class and method decorators
  • Leverage metadata reflection in frameworks

Mental model

Decorators are higher-order functions applied to classes, methods, accessors, and fields during class definition, wrapping target elements with meta-programming behaviors.

Class Definition Evaluation
Execute Decorator Factory
Attach Metadata to Reflect Target
Return Wrapped Class/Method
Conceptual teaching model synthesized from:TypeScript 5.4 Language Specification & Type System Mechanics

Theory

TypeScript 5.0 introduced native Stage 3 TC39 decorators which operate without experimentalDecorators. Stage 3 decorators receive context objects containing metadata registries (context.metadata). Frameworks like NestJS use metadata reflection to dynamically wire controllers, dependency injectors, and ORM entity mappings.

typescript(21 lines)
1export function LogExecutionTime<This, Args extends any[], Return>(
2 target: (this: This, ...args: Args) => Return,
3 context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
4) {
5 const methodName = String(context.name);
6 return function (this: This, ...args: Args): Return {
7 const start = performance.now();
8 const result = target.call(this, ...args);
9 const elapsed = (performance.now() - start).toFixed(2);
10 console.log(`[LOG]: Method '${methodName}' executed in ${elapsed}ms`);
11 return result;
12 };
13}
14
15export class OrderService {
16 @LogExecutionTime
17 processOrder(orderId: string): { status: string } {
18 return { status: `Order ${orderId} processed` };
19 }
20}

Alternatives and trade-offs

  • Stage 3 Decorators (TS 5.0+): Standardized, clean type safety; does not require experimentalDecorators.
  • Legacy Experimental Decorators (TS 4.x): Required experimentalDecorators: true and emitDecoratorMetadata.

Failure modes and misconceptions

  1. Decorator execution timing: Decorators run once when the class is defined/imported, NOT when instances are instantiated.
  2. Context this binding: Arrow functions inside decorators can break explicit this receiver bindings.
Reflect before revealing the guide

Decision scenario

Use Stage 3 TC39 decorators with explicit ClassMethodDecoratorContext parameters for new TypeScript 5.x codebases to avoid legacy polyfill requirements.

Learning outcomes

  • Differentiate Stage 3 TC39 decorators from legacy experimental decorators.
  • Author type-safe class method decorators with execution context objects.
  • Integrate metadata reflection into enterprise framework architectures.

Trade-offs

Decorators provide clean declarative syntax for cross-cutting concerns (logging, auth, validation), but execute at module evaluation time rather than instance runtime.

Prerequisites & Related Concepts (2)

Private notes

0 words
Next