How to use decorators in TypeScript
· Category: TypeScript
Short answer
Decorators are experimental functions that annotate and modify classes and their members at design time. Enable them with experimentalDecorators in tsconfig.json.
Steps
- Enable decorators in tsconfig.json.
- Create a class decorator:
function sealed(constructor: Function) { ... } - Apply it:
@sealed class Greeter { } - Create method decorators that receive target, property key, and descriptor.
- Use
reflect-metadatafor runtime type information.
Tips
- Decorators are widely used in frameworks like NestJS and Angular for dependency injection and routing.
- The TC39 proposal for standard decorators differs from TypeScript's experimental implementation.
Common issues
- Forgetting to enable
experimentalDecoratorscauses a compiler error. - Decorator metadata requires
emitDecoratorMetadataand thereflect-metadatapolyfill.