Sobes.tech
Junior — Middle

Have you used the Decorator pattern in TypeScript to extend object functionality?

sobes.tech AI

Answer from AI

The Decorator pattern in TypeScript is used for dynamically extending the functionality of objects without modifying their original code. This is achieved by creating wrappers (decorators) that add new behavior.

Example of using the Decorator pattern in TypeScript:

interface Component {
  operation(): string;
}

class ConcreteComponent implements Component {
  operation(): string {
    return "Core functionality";
  }
}

class Decorator implements Component {
  protected component: Component;

  constructor(component: Component) {
    this.component = component;
  }

  operation(): string {
    return this.component.operation();
  }
}

class ConcreteDecorator extends Decorator {
  operation(): string {
    return `Decorated -> ${super.operation()}`;
  }
}

// Usage
const simple = new ConcreteComponent();
const decorated = new ConcreteDecorator(simple);
console.log(decorated.operation()); // Outputs: Decorated -> Core functionality

Thus, objects can be extended without changing their original code, which is convenient for adding new features or logging.