BehavioralTypeScriptverifiedVerified

Chain of Responsibility Pattern in TypeScript

Passes a request along a chain of handlers, where each handler decides to process it or pass it to the next handler in the chain.

How to Implement the Chain of Responsibility Pattern in TypeScript

1Step 1: Define the request type and abstract handler

interface Request {
  type: string;
  payload: unknown;
}

abstract class Handler {
  private next: Handler | null = null;

  setNext(handler: Handler): Handler {
    this.next = handler;
    return handler;
  }

  handle(request: Request): string | null {
    if (this.next) {
      return this.next.handle(request);
    }
    return null;
  }
}

2Step 2: Implement concrete handlers

class AuthHandler extends Handler {
  handle(request: Request): string | null {
    if (request.type === "auth") {
      return "Handled by AuthHandler";
    }
    return super.handle(request);
  }
}

class ValidationHandler extends Handler {
  handle(request: Request): string | null {
    if (request.type === "validate") {
      return "Handled by ValidationHandler";
    }
    return super.handle(request);
  }
}

class LoggingHandler extends Handler {
  handle(request: Request): string | null {
    console.log(`Logging: ${request.type}`);
    return super.handle(request);
  }
}

3Step 3: Build the chain and process requests

const auth = new AuthHandler();
const validation = new ValidationHandler();
const logging = new LoggingHandler();

logging.setNext(auth).setNext(validation);

// Process requests
logging.handle({ type: "auth", payload: {} });
logging.handle({ type: "validate", payload: {} });

Chain of Responsibility Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Chain of Responsibility Pattern in the Real World

Like a customer support escalation: your call starts with a front-line agent. If they can’t resolve it, they transfer you to a specialist. If the specialist can’t help, it goes to a manager. Each level either handles it or passes it up the chain.