Created
May 10, 2020 13:20
-
-
Save khalidx/5bd1f71dee79b9daa64b17c7f1d0a9b0 to your computer and use it in GitHub Desktop.
A typed event emitter for TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This lets you emit and listen for events in a type-safe manner | |
// Awesome! | |
import { EventEmitter } from 'events' | |
type Type<Name> = { type: Name } | |
type Value<Type> = { value: Type } | |
export type TypedValue<T, V> = Type<T> & Value<V> | |
// These are some examples of typed events. One expects a string payload, and the other a number. | |
// You can add your custom events here! | |
export type EventOne = TypedValue<'EventOne', { payload: string }> | |
export type EventTwo = TypedValue<'EventTwo', { payload: number }> | |
type Types = EventOne | EventTwo | |
const bus: EventEmitter = new EventEmitter() | |
// Call on() to listen to an event | |
export const on = <T extends Types> (type: Pick<T, 'type'>, listener: (value: T) => void) => { | |
console.log('registering event handler for type', type.type) | |
bus.addListener(type.type, listener) | |
} | |
// Call emit() to publish a specific type of event | |
export const emit = <T extends Types> (type: T) => { | |
console.log('emitting event of type', type.type) | |
bus.emit(type.type, type) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment