Parameter Decorators

1. Welcome and Icebreaker:

  • If you could annotate any input you receive in life, what would you mark and why?

2. Outline the Session:

  • We’ll learn about parameter decorators in TypeScript: how to create and use them.
  • Learning Outcomes: Understand how to write decorators that add metadata or validation to method parameters.
  • Let’s annotate our parameters!

3. Concept Explanation:

  • Parameter Decorators are functions applied to method parameters.
  • They receive the target object, method name, and parameter index.
  • Can be used to add metadata, validation, or inject dependencies.
  • Syntax: @DecoratorName before a parameter.

4. Live Coding Demonstration:

function LogParam(target: any, propertyKey: string, parameterIndex: number) {
  const existingLoggedParams: number[] = Reflect.getOwnMetadata('log_params', target, propertyKey) || [];
  existingLoggedParams.push(parameterIndex);
  Reflect.defineMetadata('log_params', existingLoggedParams, target, propertyKey);
}

class Service {
  greet(@LogParam name: string) {
    console.log(`Hello, ${name}`);
  }
}

const service = new Service();
service.greet('Alice');

5. Tasks:

  • Short Exercise:
    1. Write a parameter decorator that logs the parameter index.
    2. Write a decorator that adds metadata to a parameter.
    3. Try using a parameter decorator to validate input.