How to Implement the Mediator Pattern in TypeScript
Implement the Mediator pattern in TypeScript so components talk through one coordinator instead of each other, with a chat room example, typed events and tests.

The Mediator pattern replaces a web of direct connections between objects with a single coordinator. When ten components each hold references to several of the others, nobody can change one without checking the rest, and the interaction rules are scattered across all of them. A mediator becomes the one place where those rules live: components tell the mediator what happened, and the mediator decides who needs to know and what to do. This post shows how to implement the Mediator pattern in TypeScript 5.9 on Node.js 24, using a chat room first and a form coordinator second, with typed messages, the mediator's tendency to become a god object, a comparison with Observer, and tests, with the output of each sample.
It sits close to the Observer pattern in TypeScript, which also decouples senders from receivers, and to the Facade pattern, which simplifies a subsystem without coordinating peers. The differences are explained below.
The problem: everyone knows everyone
A chat room where each user holds references to the others.
class User {
peers: User[] = [];
constructor(readonly name: string) {}
say(text: string): void {
for (const peer of this.peers) {
if (peer !== this) peer.hear(this.name, text);
}
}
hear(from: string, text: string): void {
console.log(`[${this.name}] ${from}: ${text}`);
}
}
const ada = new User("Ada");
const lin = new User("Lin");
const bo = new User("Bo");
for (const u of [ada, lin, bo]) u.peers = [ada, lin, bo];
ada.say("hello");[Lin] Ada: hello
[Bo] Ada: helloEvery user depends on every other user, so a new rule, such as muting a user or sending a private message, has to be added to User, and each user needs to be kept in sync with the peer list. The number of connections grows with the square of the number of users.
The mediator
Users talk only to the room. The room knows who is present and applies the rules.
interface ChatMediator {
broadcast(from: string, text: string): void;
direct(from: string, to: string, text: string): void;
}
class ChatUser {
constructor(
readonly name: string,
private readonly room: ChatMediator,
) {}
say(text: string): void {
this.room.broadcast(this.name, text);
}
whisper(to: string, text: string): void {
this.room.direct(this.name, to, text);
}
receive(from: string, text: string, kind: "public" | "private"): void {
console.log(`[${this.name}] ${kind} from ${from}: ${text}`);
}
}
class ChatRoom implements ChatMediator {
private readonly users = new Map<string, ChatUser>();
private readonly muted = new Set<string>();
join(name: string): ChatUser {
const user = new ChatUser(name, this);
this.users.set(name, user);
return user;
}
mute(name: string): void {
this.muted.add(name);
}
broadcast(from: string, text: string): void {
if (this.muted.has(from)) return;
for (const [name, user] of this.users) {
if (name !== from) user.receive(from, text, "public");
}
}
direct(from: string, to: string, text: string): void {
const target = this.users.get(to);
if (!target) throw new Error(`no user named ${to}`);
target.receive(from, text, "private");
}
}
const room = new ChatRoom();
const ada = room.join("Ada");
const lin = room.join("Lin");
const bo = room.join("Bo");
ada.say("hello");
lin.whisper("Bo", "meet at noon");
room.mute("Ada");
ada.say("is anyone there?");[Lin] public from Ada: hello
[Bo] public from Ada: hello
[Bo] private from Lin: meet at noonUsers hold a reference to one object, the room, and never to each other. The rules about muting and private messages are in ChatRoom, in one place, and a user class has no idea they exist. After room.mute("Ada"), the last message produces no output, because the mediator drops it. Adding a rule such as rate limiting is a change to one class.
Components and a coordinator
The pattern is common in user interfaces, where widgets should not know about each other. A form with a country field, a state field and a submit button is a typical case: the state list depends on the country, and the button is enabled only when everything is valid.
type FormEvent =
| { type: "countryChanged"; country: string }
| { type: "stateChanged"; state: string };
interface FormMediator {
notify(event: FormEvent): void;
}
class FormCoordinator implements FormMediator {
states: string[] = [];
selectedState: string | null = null;
canSubmit = false;
private static readonly STATES: Record<string, string[]> = {
US: ["CA", "NY"],
CA: ["ON", "QC"],
};
notify(event: FormEvent): void {
switch (event.type) {
case "countryChanged":
this.states = FormCoordinator.STATES[event.country] ?? [];
this.selectedState = null;
this.canSubmit = false;
break;
case "stateChanged":
this.selectedState = event.state;
this.canSubmit = this.states.includes(event.state);
break;
}
}
}
const form = new FormCoordinator();
form.notify({ type: "countryChanged", country: "US" });
console.log(form.states, form.canSubmit);
form.notify({ type: "stateChanged", state: "NY" });
console.log(form.selectedState, form.canSubmit);
form.notify({ type: "countryChanged", country: "CA" });
console.log(form.states, form.selectedState, form.canSubmit);[ 'CA', 'NY' ] false
NY true
[ 'ON', 'QC' ] null falseThe coordinator holds the dependency rules: changing the country rebuilds the state list and clears the selection, which also disables submission until a state from the new list is chosen. The last line shows that, after the country changed from the US to Canada, the old state NY is gone and the button is off. If each widget handled this itself, the state field would have to know about the country field and the button would have to know about both.
The events are a discriminated union, so inside each case TypeScript knows which fields exist: event.country is available only for countryChanged. To make a forgotten case a compile error, add a default branch that assigns event to a variable of type never; if a new event type is added to the union and not handled, that assignment stops compiling.
Typed messages
A mediator that accepts arbitrary strings turns into a stringly typed event bus where typos pass unnoticed. Use a map from event names to payload types, and let TypeScript check both sides.
interface Events {
userJoined: { name: string };
messageSent: { from: string; text: string };
}
type Handler<K extends keyof Events> = (payload: Events[K]) => void;
class Hub {
private readonly handlers: { [K in keyof Events]?: Handler<K>[] } = {};
on<K extends keyof Events>(event: K, handler: Handler<K>): void {
(this.handlers[event] ??= []).push(handler);
}
emit<K extends keyof Events>(event: K, payload: Events[K]): void {
for (const handler of this.handlers[event] ?? []) handler(payload);
}
}
const hub = new Hub();
hub.on("userJoined", ({ name }) => console.log(`welcome ${name}`));
hub.on("messageSent", ({ from, text }) => console.log(`${from}: ${text}`));
hub.emit("userJoined", { name: "Ada" });
hub.emit("messageSent", { from: "Ada", text: "hi" });welcome Ada
Ada: hihub.emit("userJoined", { text: "x" }) is a compile error, because the payload type is looked up by the event name. This is a mediator in its lightest form: components know the hub and the event names, and the hub does no coordination of its own. Whether to call it a mediator or an event bus depends on whether it contains rules or only forwards messages.
Mediator versus Observer
The two patterns are easy to confuse because both decouple senders from receivers. In Observer, a subject publishes changes and any number of observers subscribe; the relationship is one-to-many, and the subject does not care who listens. In Mediator, peers talk to the mediator, which knows them and applies logic about who should react: the relationship is many-to-many, centralized. Use Observer when you want broadcasting without logic, and Mediator when the interaction itself has rules that you want in one place.
The god object risk
The mediator's weakness is that all the interaction logic piles up in one class. A form coordinator that starts with two fields and ends with forty becomes the hardest class in the codebase, and every change touches it. The pattern moves complexity from the connections between objects into the mediator; it does not make it disappear. Keep the mediator manageable by splitting it by area, for example one coordinator per form section, and by pushing rules that belong to a single component back into that component. If a rule involves only the country field, it should live there.
Testing a mediator
Test the rules by driving the mediator with events and checking the resulting state, with no UI and no real components.
import { test } from "node:test";
import assert from "node:assert/strict";
test("changing the country clears the selected state", () => {
const form = new FormCoordinator();
form.notify({ type: "countryChanged", country: "US" });
form.notify({ type: "stateChanged", state: "NY" });
form.notify({ type: "countryChanged", country: "CA" });
assert.equal(form.selectedState, null);
assert.equal(form.canSubmit, false);
});ā changing the country clears the selected stateBecause components depend only on the mediator interface, tests of a component can pass a fake mediator that records the events the component sends.
When to use it
Use a mediator when many objects interact in complicated but well-defined ways and the connections between them have become hard to follow: chat rooms, air traffic control, form validation, dialog boxes, game entity coordination. Avoid it when only two objects talk to each other, since a direct reference is simpler, or when the interactions are simple broadcasts, where an event emitter is enough.
Keeping mediated components reusable
A hidden benefit of the pattern is reuse. A component that depends only on a small mediator interface can be moved to another screen or another application by providing a different mediator. The country dropdown does not know that a state list exists, so the same dropdown works on a checkout form, a profile page and a settings dialog, each with its own coordinator that decides what the change means there.
To preserve that benefit, keep the mediator interface narrow and in the vocabulary of the component. The dropdown should say "my value changed", not "update the state list". The second is a command for a specific peer, and it ties the component to the layout it was first written for. The first is a fact, and any mediator can react to it.
Be careful with return values from the mediator. If a component asks the mediator a question, such as "may I submit?", it depends on the mediator's answer, and tests need a fake that gives answers. Prefer fire-and-forget notifications where possible, and let the mediator push state back to components through their own methods, so that the data flows in one direction and is easy to follow.
Finally, log events when you are building a coordinator. A line for each event received and each state change makes the sequence of a bug visible without a debugger, and it doubles as documentation of how the components interact in practice.


