basarat / typescript-book

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹
https://basarat.gitbook.io/typescript/
Other
20.77k stars 2.54k forks source link

TypedEvent alternative #580

Closed binier closed 4 years ago

binier commented 4 years ago

Unless target platform isn't NodeJS, creating custom class with custom implementation just to get type-checking is probably overkill.

Current implementation:

Wouldn't it be better if we simply define custom typings for the existing EventEmitter implementation and export it? Wrote small library that does just that.

Sample:

import { TypedEmitter } from 'tiny-typed-emitter';

interface MyEvents {
  'added': (el: string, wasNew: boolean) => void;
  'deleted': (deletedCount: number) => void;
}

const ee = new TypedEmitter<MyEvents>();

ee.emit('added', 'el', true);
ee.on('added', (el, wasNew) => console.log(el, wasNew));

ee.emit('deleted', 5);
ee.on('deleted', (count) => console.log(count));
basarat commented 4 years ago

It wasn't meant as an implementation you must / should use. Was based on a discussion on what you should look for when using TypeScript.

Thanks for sharing your implementation though :rose: