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

  1. Enable decorators in tsconfig.json.
  2. Create a class decorator: function sealed(constructor: Function) { ... }
  3. Apply it: @sealed class Greeter { }
  4. Create method decorators that receive target, property key, and descriptor.
  5. Use reflect-metadata for 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 experimentalDecorators causes a compiler error.
  • Decorator metadata requires emitDecoratorMetadata and the reflect-metadata polyfill.