Skip to content

Commit

Permalink
Add the readme doc comment to the Emittery class for clarity on using…
Browse files Browse the repository at this point in the history
… typed emitters
  • Loading branch information
airhorns committed Dec 22, 2020
1 parent 34a64f2 commit e40fc77
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,39 @@ type DatalessEventNames<EventData> = {
[Key in keyof EventData]: EventData[Key] extends undefined ? Key : never;
}[keyof EventData];


/**
Emittery is a strictly typed, fully async EventEmitter implementation. Event listeners can be registered with `on` or `once`, and events can be emitted with `emit`.
`Emittery` has a generic `EventData` type that can be provided by users to strongly type the list of events and the data passed to the listeners for those events. Pass an interface of {[eventName]: undefined | <eventArg>}, with all the event names as the keys and the values as the type of the argument passed to listeners if there is one, or `undefined` if there isn't.
```ts
import Emittery = require('emittery');
const emitter = new Emittery<
// Pass `{[eventName: <string | symbol>]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
// A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
{
open: string,
close: undefined
}
>();
// Typechecks just fine because the data type for the `open` event is `string`.
emitter.emit('open', 'foo\n');
// Typechecks just fine because `close` is present but points to undefined in the event data type map.
emitter.emit('close');
// TS compilation error because `1` isn't assignable to `string`.
emitter.emit('open', 1);
// TS compilation error because `other` isn't defined in the event data type map.
emitter.emit('other');
```
*/
declare class Emittery<
EventData = { [eventName: string]: any },
EventData = { [eventName: string]: any }, // TODO: switch this index signature to include Symbols when https://github.com/microsoft/TypeScript/issues/1863 ships. If you want to use symbol keys right now, you need to pass an interface with those symbol keys explicitly listed.
DatalessEvents = DatalessEventNames<EventData>
> {
/**
Expand Down

0 comments on commit e40fc77

Please sign in to comment.