Patterns & principles · 4 of 10 · 12 min read
Observer and Pub/Sub
A typed event emitter — one event map, and every emit and on call checked against it, payload included.
- Design patterns
Observer is one object notifying a list of interested parties when something changes. In JavaScript the event name and the payload are both strings and objects nobody checks; in TypeScript a single event map makes every subscription and every emission type-safe.
The untyped version, and what goes wrong
// The shape most codebases start with:
type AnyHandler = (payload: any) => void;
class LooseEmitter {
private handlers = new Map<string, AnyHandler[]>();
on(event: string, handler: AnyHandler) {
this.handlers.set(event, [...(this.handlers.get(event) ?? []), handler]);
}
emit(event: string, payload: unknown) {
for (const handler of this.handlers.get(event) ?? []) handler(payload);
}
}
const loose = new LooseEmitter();
loose.on("userLoggedIn", (user) => console.log(user.nmae)); // typo, no error
loose.emit("userLogedIn", {}); // typo, no error, nothing fires
Both typos compile and both fail silently — the handler never runs, or runs with undefined. This
is the single most common place a JavaScript codebase loses track of itself, and it is entirely
fixable.
The typed emitter
interface Events {
userLoggedIn: { id: string; name: string };
itemAdded: { itemId: string; quantity: number };
cleared: void;
}
type Handler<T> = T extends void ? () => void : (payload: T) => void;
class Emitter<E extends Record<string, unknown>> {
#handlers: { [K in keyof E]?: Set<Handler<E[K]>> } = {};
on<K extends keyof E>(event: K, handler: Handler<E[K]>): () => void {
(this.#handlers[event] ??= new Set()).add(handler);
return () => void this.#handlers[event]?.delete(handler);
}
emit<K extends keyof E>(event: K, ...args: E[K] extends void ? [] : [E[K]]): void {
for (const handler of this.#handlers[event] ?? []) {
(handler as (payload?: E[K]) => void)(args[0]);
}
}
}
const emitter = new Emitter<Events>();
const off = emitter.on("userLoggedIn", (user) => console.log(user.name));
emitter.on("cleared", () => console.log("cleared"));
emitter.emit("userLoggedIn", { id: "1", name: "Ana" });
emitter.emit("cleared");
// emitter.emit("userLogedIn", {}); // not a key of Events
// emitter.emit("userLoggedIn", { id: "1" }); // 'name' is missing
off();
Four things to notice, because each one answers a question an interviewer is likely to ask.
The event map is the single declaration. Events is where a new event is added, and
everything else follows from keyof.
E[K] connects the name to the payload. The handler’s parameter is not any and not a union
of every payload — it is the payload for that event.
on returns an unsubscribe function. The caller holds the only thing they need to detach, and
they do not have to keep a reference to the handler. A removeListener(event, handler) API
requires the caller to keep the exact same function reference, which is the most common cause of a
listener that never goes away.
The rest-parameter trick handles payload-less events. ...args: E[K] extends void ? [] : [E[K]]
makes emit("cleared") legal and emit("cleared", {}) an error, with one signature.
Observer versus Pub/Sub
| Observer | Pub/Sub | |
|---|---|---|
| Who notifies | the subject itself | a broker in the middle |
| Does the subject know its listeners | yes, it holds the list | no |
| Coupling | subject to observers | both to the broker’s event names |
| Typing | the subject’s own event map | a shared map, imported by both sides |
| Typical in | a model, a store, a form field | an app-wide bus, a worker boundary |
The typed version of the distinction is where the event map lives. For Observer it belongs to the subject; for Pub/Sub it is a module both sides import, and that shared file becomes the contract:
// events.ts — the contract
export interface AppEvents {
"cart:item-added": { itemId: string; quantity: number };
"cart:cleared": void;
"auth:logged-out": { reason: "expired" | "manual" };
}
Namespaced keys are worth the colons: they stay readable in a long map, and
`cart:${string}` becomes a usable template-literal filter when you want all of one domain’s
events.
A typed observable value
The narrower, more common cousin — one value with subscribers:
class Observable<T> {
#value: T;
#listeners = new Set<(value: T, previous: T) => void>();
constructor(initial: T) { this.#value = initial; }
get value() { return this.#value; }
set value(next: T) {
if (Object.is(next, this.#value)) return; // no notify on no change
const previous = this.#value;
this.#value = next;
for (const listener of this.#listeners) listener(next, previous);
}
subscribe(listener: (value: T, previous: T) => void): () => void {
this.#listeners.add(listener);
return () => void this.#listeners.delete(listener);
}
}
const count = new Observable(0);
const off = count.subscribe((value, previous) => console.log(previous, "->", value));
count.value = 1;
count.value = 1; // nothing — Object.is guard
off();
console.log(count.value);
Object.is rather than === so NaN does not notify forever and -0 does not notify at all.
This is the core of every signal and store library, and it is 20 lines.
Errors in a listener
One detail with real consequences: a throwing listener must not stop the others.
const listeners = new Set<() => void>([
() => { throw new Error("first one fails"); },
() => console.log("second one still runs"),
]);
for (const listener of listeners) {
try {
listener();
} catch (error) {
console.error("listener failed:", error instanceof Error ? error.message : error);
}
}
Without the try, one buggy subscriber silently disables every subscriber registered after it —
and the symptom appears in an unrelated feature.
Note also that Set iteration sees items added during the loop. Copying with [...listeners]
before iterating is the fix when a handler can subscribe or unsubscribe.
Common mistakes
(payload: any) => void as the handler type
Mistake. One handler type for every event.
Why it fails. Every property access inside every handler is unchecked, which is exactly where
the typos live.
What to do instead. An event map and E[K], so each handler’s payload is its own.
No way to unsubscribe
Mistake. on(event, handler) returning void.
Why it fails. Detaching requires the identical function reference, so an inline arrow can
never be removed — and a component that subscribes on mount leaks on every remount.
What to do instead. Return an unsubscribe function, and call it in the teardown.
Emitting from inside a handler
Mistake. A listener that emits the same event it is handling. Why it fails. Infinite recursion, or a mutation of the set being iterated. The types cannot see it. What to do instead. Iterate a copy, and keep handlers free of emissions — queue the follow-up work instead.
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
How does a typed Observer differ from the JavaScript version?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.