Domain-Driven Design - Aggregate Roots in TypeScript

Before you look at the Aggregate Roots example in TypeScript, you can see at my post on what Aggregate Roots are in Domain-Driven Design.

Aggregate Root base class in TypeScript

abstract class AggregateRoot extends Entity {
  private readonly _domainEvents: DomainEvent[] = [];

  protected constructor(id: UniqueId) {
    super(id);
  }

  get domainEvents(): DomainEvent[] {
    return Object.assign([], this._domainEvents);
  }

  public addDomainEvent(domainEvent: DomainEvent): void {
    this._domainEvents.push(domainEvent);
  }

  public clearDomainEvents(): void {
    this._domainEvents.splice(0, this._domainEvents.length);
  }
}

About this code snippet:

  • It is an abstract class: This prevents this class from being instantiated and allows to declare abstract methods.