Mental model
Decorators are higher-order functions applied to classes, methods, accessors, and fields during class definition, wrapping target elements with meta-programming behaviors.
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.
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: trueandemitDecoratorMetadata.
Failure modes and misconceptions
- Decorator execution timing: Decorators run once when the class is defined/imported, NOT when instances are instantiated.
- Context
thisbinding: Arrow functions inside decorators can break explicitthisreceiver bindings.
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.