Skip to content

Instantly share code, notes, and snippets.

@gcanti
Created November 5, 2016 08:38
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcanti/0339913a61199e796b356f7b592f28e5 to your computer and use it in GitHub Desktop.
Save gcanti/0339913a61199e796b356f7b592f28e5 to your computer and use it in GitHub Desktop.
Type safe event emitter with Flow
// A is a phantom type that ties an event instance...
class Event<A> {}
// ...to its handler
type Handler<A> = (a: A, ...rest: Array<void>) => void;

declare class EventEmitter {
  on<A, F: Handler<A>>(event: Event<A>, handler: F): void;
  emit<A>(event: Event<A>, a: A): void;
}

type User = { name: string, surname: string };
const save: Event<User> = new Event()
const emitter = new EventEmitter()

emitter.on(save, (u: User) => {})
// $ExpectError
emitter.on(save, (u: number) => {})
// $ExpectError
emitter.on(save, (u: User, unknown: number) => {})

emitter.emit(save, { name: 'Giulio', surname: 'Canti' })
// $ExpectError
emitter.emit(save, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment