Decorators: Metadata Annotations in TypeScript

1. Welcome and Icebreaker:

  • If you could add a special tag or annotation to anything in your life, what would it be and why?

2. Outline the Session:

  • We’ll learn about decorators in TypeScript: what they are, how to use them, and why they’re useful.
  • Learning Outcomes: Understand the basics of decorators and how to apply them to classes, methods, properties, and parameters.
  • Let’s decorate our code!

3. Concept Explanation:

  • Decorators are special annotations (using @) that can be attached to classes, methods, properties, or parameters to add metadata or modify behavior.
  • Decorators are an experimental feature in TypeScript and require enabling in tsconfig.json (experimentalDecorators: true).
  • Types: Class decorators, method decorators, property decorators, parameter decorators.
  • Decorators are functions that receive information about the target they decorate.

4. Live Coding Demonstration:

// Enable experimentalDecorators in tsconfig.json
// @Component decorator for a class
function Component(target: Function) {
  target.prototype.isComponent = true;
}

@Component
class MyComponent {}
console.log((new MyComponent() as any).isComponent); // true

// Method decorator
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 Calculator {
  @Log
  add(a: number, b: number) {
    return a + b;
  }
}
const calc = new Calculator();
calc.add(2, 3);

5. Tasks:

  • Short Exercise:
    1. Enable experimentalDecorators in your tsconfig.json.
    2. Write a class decorator that adds a property to a class.
    3. Write a method decorator that logs method calls.
    4. Try creating a property or parameter decorator.