Observer Pattern With Typed Subjects

Implement a typed observer pattern with subject and observer interfaces for type-safe event notification.

TypescriptData Fetching

Code

typescriptsnippet
1 line
interface Observer<T>{update(data:T):void;}class Subject<T>{private observers:Set<Observer<T>>=new Set();subscribe(o:Observer<T>):()=>void{this.observers.add(o);return()=>this.observers.delete(o);}unsubscribe(o:Observer<T>){this.observers.delete(o);}notify(data:T){for(const o of this.observers)o.update(data);}}export function createSubject<T>(){return new Subject<T>();}export function createObserver<T>(handler:(data:T)=>void):Observer<T>{return{update:handler};}

How it works

Observer Pattern With Typed Subjects comes down to the class Subject and the functions createSubject and createObserver.

A fresh value is allocated for the result; the arguments stay untouched.

Putting it to use

Import createSubject from the file and call it — the rest of the code is implementation detail.

Interactive Tools for This Topic

FAQ

Does `createSubject` modify its input?
No mutation happens — the function reads its input and returns a new value.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `createSubject`, `createObserver` at load time.