Typed Event Emitter
NOTE: REQUIRES TYPESCRIPT 3.0
A TypeScript library for strongly typed event emitters in 0 kB. Declare events using a simple interface mapping event names to their payloads to get stricter versions of
on, and other common EventEmitter APIs. Works with any kind of EventEmitter.
npm i strict-event-emitter-types
;// define your events// grab an event emitter;// Create strict event emitter types;// now enjoy your strongly typed EventEmitter API!🎉ee.on'request',... ;// r and resp are contextually typed to Request and Responseee.on'somethingElse';// Error: unknown eventee.on'done', x;// Error: The 'done' event does not have a payloadee.emit'request', new Request;// Error: missing event payload (the response)ee.emit'request', new Request, false;// Error: incorrect payload type
Event records are interfaces or object types that map event names to the event's payload types. In the following example, three events are declared:
Each event shows one of three ways to type the event payloads:
- Function type: Parameters are the event payload. The return type is ignored.
void: A shortcut for an event with no payload, i.e.
() => void
- Anything else: A shortcut for an event with one payload, for example
(p: number) => voidcan be written as just
StrictEventEmitter<TEmitterType, TEventRecord, TEmitRecord>
The default export. A generic type that takes three type parameters:
- TEmitterType: Your EventEmitter type (e.g. node's EventEmitter or socket.io socket)
- TEventRecord: A type mapping event names to event payloads
- TEmitRecord: Optionally, a similar type mapping things you can emit.
The third parameter is handy when typing web sockets where client and server can listen to and emit different events. For example, if you are using socket.io:
// create types representing the server side and client// side sockets;;// elsewhere on server;serverSocket.on/* only events that are sent from the client are allowed */, ...serverSocket.emit/* only events that are emitted from the server are allowed */, ...// elsewhere on client;clientSocket.on/* only events that are sent from the server are allowed */, ...clientSocket.emit/* only events that are emitted from the client are allowed */, ...
Usage with Subclasses
To subclass an EventEmitter you need to cast the base EventEmitter to the strict EventEmitter before extending:
A type for a function which takes (and strictly checks) an emit event and a payload. TStrictEventEmitter is the event emitter type instantiated from StrictEventEmitter.
Useful for broadcast abstractions. It is not possible to contextually type assigments to this type, so your declarations will look something like this:
Note that the loose types for event and payload only apply inside the broadcast function (consumers will see a much stricter signature). Declaring more precise parameter types or narrowing using type guards would allow strongly-typed dispatching to emitters.