// 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, {})
Created
November 5, 2016 08:38
-
-
Save gcanti/0339913a61199e796b356f7b592f28e5 to your computer and use it in GitHub Desktop.
Type safe event emitter with Flow
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment