theory.ts

Decorators

Class Decorators

Class decorators modify a class at definition time, commonly used for metadata and logging.

  • A class decorator is a function that takes the constructor as an argument.
  • Runs when the class is declared, not when instantiated.
  • Used in frameworks like Angular and NestJS for metadata management.
// Logging class creation time
function WithTimestamp(constructor: Function) {
  console.log(`Class ${constructor.name} was created at ${new Date().toISOString()}`);
}

@WithTimestamp
class Example {}

// Logs: "Class Example was created at YYYY-MM-DDTHH:MM:SS.ZZZZ"