Class Decorators

1. Welcome and Icebreaker:

  • If you could add a superpower to any class of objects, what would it be?

2. Outline the Session:

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

3. Concept Explanation:

  • Class Decorators are functions applied to class declarations.
  • They can add properties, modify prototypes, or even replace the class constructor.
  • Syntax: @DecoratorName above a class definition.
  • Decorators receive the class constructor as their argument.

4. Live Coding Demonstration:

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

@Sealed
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

const p = new Person("Alice");
console.log(Object.isSealed(Person)); // true
console.log(Object.isSealed(p)); // false (only the prototype is sealed)

// Class decorator that adds a static property
function Version(version: string) {
  return function (constructor: Function) {
    constructor.prototype.version = version;
  };
}

@Version("1.0.0")
class App {}
console.log((new App() as any).version); // 1.0.0

5. Tasks:

  • Short Exercise:
    1. Write a class decorator that logs when a class is created.
    2. Write a decorator that adds a static property to a class.
    3. Try combining multiple class decorators.