CodeToLive

TypeScript Decorators

Decorators are a special kind of declaration that can be attached to classes, methods, properties, or parameters to modify their behavior.

Class Decorators

Class decorators are applied to the constructor of a class.


function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return "Hello, " + this.greeting;
  }
}
      

Method Decorators

Method decorators are applied to methods within a class.


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

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

Property Decorators

Property decorators are applied to properties within a class.


function format(target: any, propertyKey: string) {
  let value = target[propertyKey];
  const getter = () => value;
  const setter = (newVal: string) => {
    value = newVal.toUpperCase();
  };
  Object.defineProperty(target, propertyKey, {
    get: getter,
    set: setter,
  });
}

class Greeter {
  @format
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
}
      
Next: TypeScript Modules