Dung (Donny) Nguyen

Senior Software Engineer

Custom Decorator for Class Methods

A custom decorator for class methods in TypeScript is a special function that allows you to augment or modify the behavior of a class method in a declarative, reusable way. Decorators are applied using the @ symbol above the target method and receive specific parameters related to the class and the method being decorated.[1][2][4]

Basic Syntax and Parameters

A method decorator in TypeScript typically has the following signature:

function myDecorator(
  target: Object,
  propertyKey: string | symbol,
  descriptor: PropertyDescriptor
): PropertyDescriptor | void {
  // Your logic here
}

Example: Logging Decorator

Here’s a practical example that logs before and after a method is called:

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

class Example {
  @log
  greet(name: string) {
    return `Hello, ${name}`;
  }
}

Customizing Decorators

Decorators can also be factories, meaning you can pass arguments to them:

function logWithPrefix(prefix: string) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const original = descriptor.value;
    descriptor.value = function (...args: any[]) {
      console.log(`${prefix} ${propertyKey}:`, args);
      return original.apply(this, args);
    };
    return descriptor;
  };
}
class Demo {
  @logWithPrefix("[Demo]")
  doTask(a: number) {
    return a * 2;
  }
}

Notes and Limitations

1 2 3 4 5 6 7 8 9 10