Mediator Pattern Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Mediator Pattern runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓The runtime is EventTarget or EventEmitter; what TypeScript contributes is a typed event map, an interface whose keys are event names and whose values are payload types, combined with generic on and emit signatures constrained by keyof.
- ✓Declare the event map once and derive every signature from it with keyof and indexed access, so adding an event is a one-line change that immediately type-checks every publisher and subscriber.
- ✓The TypeScript trap: Typing the hub proves nothing about listeners registered elsewhere: DOM EventTarget dispatches to anything added by any code, so a typed wrapper is a convention over an untyped runtime and a stray addEventListener with a wrong payload compiles in another file and fails at run time.
- ✓Nothing at run time. Compile time is the consideration: an event map with hundreds of entries makes every generic on and emit instantiate a large union, and combined with template literal types for namespacing it is a common source of slow completions in editors.
What Mediator Pattern actually is
Mediator Pattern in TypeScript: what you actually reach for
TypeScript implementation
interface Events {
'user:saved': { readonly id: string };
'user:deleted': { readonly id: string; readonly reason: string };
}
class TypedHub {
#target = new EventTarget();
// Property-style handler type gets STRICT (contravariant) checking.
on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): () => void {
const wrapped = (e: Event) => handler((e as CustomEvent<Events[K]>).detail);
this.#target.addEventListener(event, wrapped);
return () => this.#target.removeEventListener(event, wrapped);
}
emit<K extends keyof Events>(event: K, payload: Events[K]): void {
this.#target.dispatchEvent(new CustomEvent(event, { detail: payload }));
}
}
const hub = new TypedHub();
const off = hub.on('user:deleted', (p) => console.log(p.reason));
hub.emit('user:deleted', { id: 'u1', reason: 'gdpr' });
off();
// hub.emit('user:saved', { id: 'u1', reason: 'x' }); // error: excess property
// hub.on('user:svaed', () => {}); // error: misspelled eventThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Mediator Pattern?
The runtime is EventTarget or EventEmitter; what TypeScript contributes is a typed event map, an interface whose keys are event names and whose values are payload types, combined with generic on and emit signatures constrained by keyof. That turns a misspelled event name and a wrong payload shape into compile errors, which is the entire reason to reach for a custom hub rather than the untyped platform one. Since TypeScript 4.1, template literal types can also derive namespaced event names.
What is the most common TypeScript mistake when implementing Mediator Pattern?
Typing the hub proves nothing about listeners registered elsewhere: DOM EventTarget dispatches to anything added by any code, so a typed wrapper is a convention over an untyped runtime and a stray addEventListener with a wrong payload compiles in another file and fails at run time. The more common bug is subtler: because handler parameters are checked bivariantly when declared method-style, a handler that accepts a NARROWER payload than the event actually carries is accepted, so a subscriber written against an older payload shape type-checks and then reads undefined fields.
How does Mediator Pattern actually perform in TypeScript?
Nothing at run time. Compile time is the consideration: an event map with hundreds of entries makes every generic on and emit instantiate a large union, and combined with template literal types for namespacing it is a common source of slow completions in editors. Splitting the map per feature area keeps each instantiation small. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.