TypeScript Decorators: Metadata and Annotations

Decorators add metadata to classes, methods, and properties. They’re experimental but widely used in frameworks like Angular and NestJS.

Enable Decorators

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

Class Decorator

function Controller(path: string) {
  return function(target: Function) {
    Reflect.defineMetadata('path', path, target);
  };
}

@Controller('/users')
class UserController {}

Method Decorator

function Log(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function(...args: any[]) {
    console.log(`Calling ${key} with`, args);
    return original.apply(this, args);
  };
}

class Calculator {
  @Log
  add(a: number, b: number) { return a + b; }
}

Common Uses

  • Dependency injection
  • Route definitions
  • Validation
  • Logging and timing

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.