Decorators
Decorators provide a way to add annotations and meta-programming syntax for class declarations and members. TypeScript supports both the modern Stage 3 decorators and legacy experimental decorators.Overview
Decorators are special declarations that can be attached to:- Classes
- Methods
- Accessors (getters/setters)
- Properties
- Parameters
@expression syntax, where expression evaluates to a function that will be called at runtime with information about the decorated declaration.
Stage 3 Decorators (Recommended)
Stage 3 decorators are the modern, standardized version aligned with the TC39 proposal. They are the default in TypeScript 5.0+.Enabling Stage 3 Decorators
tsconfig.json
Stage 3 decorators are enabled by default when
target is ESNext or ES2022+. No special flag is required.Class Decorators
Class decorators are applied to class declarations and can observe, modify, or replace a class definition.Method Decorators
Method decorators are applied to method declarations and can observe, modify, or replace a method definition.Property Decorators
Property decorators can observe property declarations on a class.Accessor Decorators
Accessor decorators are applied to getters or setters.Auto-Accessor Decorators
Stage 3 decorators introduce theaccessor keyword for auto-accessors:
Parameter Decorators
Parameter decorators are applied to function parameters.Legacy Decorators (Experimental)
Legacy decorators use the older experimental syntax. They are still widely used in frameworks like Angular.Enabling Legacy Decorators
tsconfig.json
Legacy vs. Stage 3 Differences
- Execution Order
- Decorator Context
- Return Values
Legacy decorators:
- Evaluate bottom-to-top
- Execute top-to-bottom
- Consistent evaluation and execution order
- More predictable behavior
Decorator Composition
Multiple decorators can be applied to a single declaration:Decorators are evaluated top-to-bottom, but executed bottom-to-top (like function composition).
Decorator Metadata
WithemitDecoratorMetadata enabled, TypeScript emits design-time type information for decorators.
Enabling Metadata
tsconfig.json
Using Metadata
Metadata Keys
TypeScript automatically emits three types of metadata:design:type
The type of the property or parameter
design:paramtypes
The types of function parameters
design:returntype
The return type of a function
Real-World Example: Dependency Injection
Common Decorator Patterns
Memoization Decorator
Validation Decorator
Timing Decorator
Best Practices
Use Stage 3 for New Projects
Prefer modern decorators for better standardization
Keep Decorators Simple
Each decorator should have a single, clear purpose
Document Side Effects
Clearly document any runtime behavior changes
Type Safety
Use proper TypeScript types in decorator implementations
Migration from Legacy to Stage 3
Related Resources
Mixins
Combine decorators with mixin patterns
Compiler Options
Configure decorator-related options