Method Decorators

1. Welcome and Icebreaker:

  • If you could automatically log or modify any action you take, what would it be?

2. Outline the Session:

  • We’ll learn about method decorators in TypeScript: how to create and use them.
  • Learning Outcomes: Understand how to write decorators that enhance or modify class methods.
  • Let’s decorate our methods!

3. Concept Explanation:

  • Method Decorators are functions applied to class methods.
  • They receive the target object, method name, and property descriptor.
  • Can be used to log, validate, or modify method behavior.
  • Syntax: @DecoratorName above a method.

4. Live Coding Demonstration:

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

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

const math = new MathOps();
math.add(2, 3);

5. Tasks:

  • Short Exercise:
    1. Write a method decorator that times how long a method takes to execute.
    2. Write a decorator that prevents a method from being called more than once.
    3. Try combining multiple method decorators on a single method.