Pub-Sub pattern in TypeScript

NISHANK KUMAR
2 min readJun 1, 2023

An example implementation of a simple pub-sub (publish-subscribe) system in TypeScript. In this example, we’ll create a basic event emitter class that allows objects to subscribe to and emit events.

Here’s the TypeScript code for the pub-sub implementation:

type EventCallback = (...args: any[]) => void;

class EventEmitter {
private events: Record<string, EventCallback[]>;
constructor() {
this.events = {};
}
public subscribe(eventName: string, callback: EventCallback): void {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
}
public unsubscribe(eventName: string, callback: EventCallback): void {
const eventCallbacks = this.events[eventName];
if (eventCallbacks) {
this.events[eventName] = eventCallbacks.filter(
(cb) => cb !== callback
);
}
}
public emit(eventName: string, ...args: any[]): void {
const eventCallbacks = this.events[eventName];
if (eventCallbacks) {
eventCallbacks.forEach((callback) => {
callback(...args);
});
}
}
}

Let’s see an example of how to use this pub-sub implementation:

const eventEmitter = new EventEmitter();

// Define event handlers
const handler1: EventCallback = (message: string) => {
console.log(`Handler 1: ${message}`);
};
const handler2: EventCallback = (message: string) => {
console.log(`Handler 2: ${message}`);
};

// Subscribe handlers to events
eventEmitter.subscribe('event1', handler1);
eventEmitter.subscribe('event1', handler2);

// Emit the event
eventEmitter.emit('event1', 'Hello, World!');

In this example, we create an instance of the EventEmitter class. We define two event handlers, handler1 and handler2, which simply log the received message. Then we subscribe both handlers to the event named 'event1'. Finally, we emit 'event1' with the message 'Hello, World!', causing both handlers to be invoked.

When you run the code, you should see the following output:

Handler 1: Hello, World!
Handler 2: Hello, World!

The event emitter allows multiple handlers to be subscribed to the same event, and when the event is emitted, all the subscribed handlers will be called with the provided arguments.

This is a basic implementation of a pub-sub system in TypeScript. Depending on your requirements, you can extend this implementation further by adding features such as wildcard event subscriptions, one-time event subscriptions, error handling, and more.

--

--