Type-safe event emitter pattern in Typescript - Time & Space Complexity
We want to understand how the time it takes to run a type-safe event emitter grows as we add more events or listeners.
Specifically, how does the number of listeners affect the work done when an event is emitted?
Analyze the time complexity of the following code snippet.
interface Events {
message: (text: string) => void;
error: (code: number) => void;
}
class EventEmitter {
private listeners: { [K in keyof Events]?: Events[K][] } = {};
on(event: K, listener: Events[K]) {
(this.listeners[event] ??= []).push(listener);
}
emit(event: K, ...args: Parameters) {
(this.listeners[event] ?? []).forEach(listener => listener(...args));
}
}
This code defines a type-safe event emitter that stores listeners and calls them when an event is emitted.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop that calls each listener when an event is emitted. - How many times: It runs once for each listener registered for that event.
When you emit an event, the time to run grows with the number of listeners for that event.
| Input Size (listeners) | Approx. Operations (listener calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of listeners. More listeners mean more calls.
Time Complexity: O(n)
This means the time to emit an event grows linearly with the number of listeners for that event.
[X] Wrong: "Emitting an event always takes the same time, no matter how many listeners there are."
[OK] Correct: Each listener must be called, so more listeners mean more work and more time.
Understanding how event emitters scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed the emitter to call only the first listener instead of all? How would the time complexity change?"
Practice
type-safe event emitter in TypeScript?Solution
Step 1: Understand type safety in event emitters
Type-safe event emitters use TypeScript types to ensure events and their data match expected types.Step 2: Identify the benefit of type safety
This prevents runtime errors by catching mismatches during development, improving code reliability.Final Answer:
It ensures events and their data match expected types, preventing runtime errors. -> Option BQuick Check:
Type safety = prevents runtime errors [OK]
- Thinking it improves runtime speed
- Assuming it logs events automatically
- Believing it allows untyped events
login (payload: string) and logout (no payload)?Solution
Step 1: Understand event payload types
Events with no payload should useundefinedto indicate no data is expected.Step 2: Check interface options
interface Events { login: string; logout: undefined; } useslogout: undefined, which correctly represents no payload for the logout event.Final Answer:
interface Events { login: string; logout: undefined; } -> Option CQuick Check:
No payload event = undefined type [OK]
- Using void which is a function return type
- Using null which means absence of value
- Using never which means impossible type
interface Events {
message: string;
error: { code: number; message: string };
}
const emitter = new TypedEmitter<Events>();
emitter.on('message', (msg) => console.log(msg));
emitter.emit('error', { code: 404, message: 'Not found' });What will be the output when the
error event is emitted?Solution
Step 1: Check registered event listeners
Only a listener for 'message' event is registered, no listener for 'error'.Step 2: Understand event emission behavior
Emitting 'error' without a listener produces no output; no automatic logging occurs.Final Answer:
No output because no listener for 'error' event is registered. -> Option AQuick Check:
Emit without listener = no output [OK]
- Assuming emit logs automatically
- Expecting runtime error without listener
- Confusing event data with console output
interface Events {
update: number;
}
const emitter = new TypedEmitter<Events>();
emitter.on('update', (data: string) => {
console.log(data);
});What is the problem with this code?
Solution
Step 1: Check event payload type in interface
The 'update' event expects anumberpayload.Step 2: Check listener callback parameter type
The callback expects astring, which mismatches the expectednumber.Final Answer:
The listener callback parameter type does not match the event payload type. -> Option DQuick Check:
Listener param type must match event payload type [OK]
- Ignoring type mismatch warnings
- Assuming any type is allowed
- Confusing event names with payload types
-
join: payload is username (string)-
leave: payload is username (string)-
message: payload is an object with user (string) and text (string)Which interface correctly defines these events for type safety?
Solution
Step 1: Analyze event payload requirements
'join' and 'leave' expect a username string; 'message' expects an object with user and text strings.Step 2: Match interface to requirements
interface ChatEvents { join: string; leave: string; message: { user: string; text: string }; } matches exactly: 'join' and 'leave' as string, 'message' as object with user and text.Final Answer:
interface ChatEvents { join: string; leave: string; message: { user: string; text: string }; } -> Option AQuick Check:
Match payload types exactly for type safety [OK]
- Using wrong payload types for events
- Omitting required object structure
- Using undefined for events that need payload
Ready to prove it?
Pass the test and this pattern moves unknown
