FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

TypeScript Decorators & Metadata

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

Freshness: current•14 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Author Stage 3 class and method decorators
  • ✓Leverage metadata reflection in frameworks
Full Technical Reference Document

Mental model

Decorators are higher-order functions evaluated once at class definition time (when JS imports and defines the class, not per object instantiation) to wrap, instrument, register, or attach metadata to classes, methods, fields, and getters/setters. Across the TypeScript ecosystem, two incompatible dialects coexist: modern TC39 Stage 3 standard decorators shipped natively in TypeScript 5.0+ (carrying strict context objects and Symbol.metadata), and legacy experimentalDecorators (reflect-metadata + emitDecoratorMetadata) still used heavily by frameworks like NestJS, TypeORM, and Angular. Knowing their signature differences, this binding traps, and runtime metadata trade-offs prevents silent boot bugs and keeps library layers cleanly decoupled.

Class Definition Evaluated at Load
Decorator Factory Receives Target & Context
Attach Metadata (Symbol.metadata / Reflect)
Run addInitializer or Wrap Target
Instantiate Class Instances Cleanly
Conceptual teaching model synthesized from:typescript-54-spec,tc39-ecma262

Theory

TypeScript 5.0 aligned cleanly with the TC39 ECMAScript Decorator standard, removing reliance on compiler-specific parameter reflection (emitDecoratorMetadata) while giving every decorator a structured context object (kind, name, static, private, addInitializer, and metadata). Legacy frameworks that automatically infer constructor injection types without passing explicit tokens (constructor(private readonly db: DbService)) continue requiring experimentalDecorators: true + emitDecoratorMetadata: true because TypeScript's type eraser intentionally strips parameter type annotations under standard Stage 3 rules.

Decorator DialectRequired tsconfig.json FlagsParameter Decorators?Type Metadata MechanismPrimary Ecosystem
TC39 Stage 3 (TS 5.0+)None (target >= ES2022 clean)Not part of base speccontext.metadata (Symbol.metadata) populated declarativelyModern Node/TS 5.x toolkits, Lit, clean method telemetry/guards
Legacy Experimental (TS 4.x compat)"experimentalDecorators": true (+ "emitDecoratorMetadata": true)Supported (@Inject(), @Param())Global reflect-metadata polyfill (Reflect.getMetadata("design:paramtypes", ...))NestJS, TypeORM, class-validator, Angular

Stage 3 Contexts, addInitializer, and Metadata Polyfills

Under TC39 Stage 3, decorators take (value, context)—where value is the decorated function/class (or undefined for field initializers returning a field-transformer) and context.addInitializer(fn) registers setup callbacks executed either once when a class completes definition (for static members) or inside every constructor invocation (for instance methods/fields, useful for auto-binding event handlers cleanly without altering prototypes globally). Notice also that Symbol.metadata currently requires a minimal polyfill ((Symbol as any).metadata ??= Symbol("Symbol.metadata")) on runtimes predating native Stage 3 shipping, whereas legacy emitDecoratorMetadata emits fragile runtime lookups against concrete classes—meaning TypeScript interfaces vanish to Object at runtime!

typescript
// Ensure Symbol.metadata exists across Node/browser runtimes supporting TS 5.2+ decorator metadata
(Symbol as { metadata?: symbol }).metadata ??= Symbol.for("Symbol.metadata");
​
export function TimedTool<This, Args extends unknown[], Return>(
originalMethod: (this: This, ...args: Args) => Promise<Return>,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<Return>>,
) {
const methodName = String(context.name);
​
// Record declarative capability metadata cleanly on context.metadata
const tracedMethods = (context.metadata.tracedMethods as string[] | undefined) ?? [];
context.metadata.tracedMethods = [...tracedMethods, methodName];
​
// Must return a regular `function` (NOT an arrow function) to preserve dynamic `this` binding
return async function (this: This, ...args: Args): Promise<Return> {
const started = performance.now();
try {
return await originalMethod.apply(this, args);
} finally {
const durationMs = (performance.now() - started).toFixed(2);
console.debug(`[TimedTool] ${methodName} finished in ${durationMs}ms`);
}
};
}
​
export class RetrievalService {
@TimedTool
async fetchContext(query: string): Promise<string[]> {
return [`result:${query}`];
}
}

Alternatives and trade-offs

  • TC39 Stage 3 Decorators (TS 5.0+): Zero experimental compiler flags, preserves strict receiver/argument/return generic typing cleanly, standardizes cross-bundler behavior (esbuild 0.21+, TypeScript 5.0+, Babel); no native parameter-level @Body() / constructor auto-injection without explicit tokens.
  • Legacy experimentalDecorators + reflect-metadata: Required for ergonomic NestJS/TypeORM class-validator ecosystems; cannot inspect TypeScript interfaces/generics (design:type resolves Array<User> merely to Array and interfaces to Object!), and breaks if experimentalDecorators is accidentally turned off in a shared monorepo tsconfig.
  • Explicit Functional Wrappers / Plain Factories (withTiming(fn), Zod + Drizzle/tRPC): Transparent call stacks, effortless tree-shaking, zero magic this binding, zero polyfills—often cleaner than decorators for React/Next.js and functional server handlers.

Failure modes and misconceptions

  1. Mixing Stage 3 & experimentalDecorators Inside One Compilation Unit: Toggling "experimentalDecorators": true completely disables Stage 3 signatures (ClassMethodDecoratorContext fails immediately) and vice versa. Keep legacy NestJS packages and Stage 3 libraries in isolated workspaces with explicit local tsconfig.json files.
  2. Using Arrow Functions Inside Method Decorators: Returning (...args) => target(...args) destroys the instance this receiver whenever the method accesses this.db or class fields, throwing runtime Cannot read properties of undefined. Always return a standard function (this: This, ...args) and invoke .apply(this, args).
  3. Expecting emitDecoratorMetadata to Preserve Interfaces or Generic Type Arguments: Writing @Inject() repo: UserRepositoryInterface emits design:paramtypes: [Object], causing NestJS DI resolution to crash at startup because TypeScript erases interfaces before runtime reflection runs. Use concrete class tokens or explicit @Inject("USER_REPO") keys.
  4. Heavy Top-Level Side Effects Breaking Tree-Shaking: Decorated classes run decorator bodies during ES module evaluation—meaning bundlers often cannot eliminate unused decorated controller classes unless cleanly isolated.
Reflect before revealing the guide

Decision scenario

Your TypeScript monorepo runs a legacy NestJS microservice alongside a modern Next.js frontend and a shared TypeScript 5.5 instrumentation SDK. Leave "experimentalDecorators": true + "emitDecoratorMetadata": true scoped strictly inside the NestJS service's local tsconfig.json (never in the root tsconfig.base.json), write shared cross-platform method wrappers either as explicit functional HOFs (traceSpan(name, fn)) for tree-shakeable Next.js code or clean TC39 Stage 3 decorators using ClassMethodDecoratorContext + regular function bindings for shared class services, and always inject interface dependencies explicitly by token rather than relying on erased TypeScript interfaces.

Learning outcomes

  • Compare TC39 Stage 3 TypeScript 5+ decorators against legacy experimentalDecorators and reflect-metadata.
  • Explain why decorator functions evaluate once at class definition time and why arrow wrappers break this binding.
  • Understand why emitDecoratorMetadata erases TypeScript interfaces/generics to Object at runtime.
  • Structure monorepo tsconfig.json boundaries cleanly so Stage 3 and legacy ecosystems never collide.

Trade-offs

Decorators consolidate cross-cutting telemetry, validation tags, and route metadata cleanly right above declarations, at the cost of hidden import-time execution order, tree-shaking friction, and strict separation between Stage 3 and legacy experimentalDecorators configs.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next