1.0.3 • Published 2 years ago
events.d.ts v1.0.3
Installation
- Install this package via npm.
$ npm i -D events.d.ts
- Use the TypeScript version of your workspace. This is necessary to load plugins from
tsconfig.json
. For instructions, see: Using the workspace version of TypeScript. - Add the plugin to your
tsconfig.json
file.{ "compilerOptions": { "baseUrl": "./", "skipLibCheck": true, "paths": { "*": ["./node_modules/events.d.ts/types"] }, "plugins": [{ "name": "events.d.ts" }] } }
Typings
EventEmitter
This class has been modified to accept an optional EventMap
as its single type argument.
class EventEmitter<Map extends EventMap = EventMap>
EventMap
An object where the keys represent the event names and the values indicate the corresponding arguments. The event arguments can be specified using an array, a tupple or the listener function signature (which is a void function). You can use optional parameters as well as rest parameters.
interface EventMap {
[eventName: string | symbol]: [...eventArgs: any[]] | ((...eventArgs: any[]) => void);
}
Usage
There is no need to import or implement any special types. Just pass a custom EventMap
as a type argument to EventEmitter
and you are good to go.
Examples
import EventEmitter from "events";
type EventMap = {
message: [string];
error: [error?: Error];
success: [body: string, ...args: [a?: number, b?: number]];
info(body: string): void;
warning: (body: string) => void;
};
Creating Instances
let myEmitter = new EventEmitter<EventMap>();
myEmitter.emit("message", "👋🏻");
// ✓
myEmitter.on("success", b => console.log(b.toLowerCase()));
// ✓: there's no need to specify the parameter's type, since it's infered
myEmitter.emit("warning", new Error());
// ✗: wrong argument type
// → "Argument of type 'Error' is not assignable to parameter of type 'string'."
myEmitter.on("error", e => console.log(e.message));
// ✗: e is an optional parameter
// → "Object is possibly 'undefined'."
myEmitter.on("message", (a, b) => console.log(a, b));
// ✗: too many parameters
// → "Argument of type [...] is not assignable to parameter of type [...]."
Extending Custom Classes
export default class MyEmitter extends EventEmitter<EventMap>{
print = (msg: string) => this.emit("message", msg);
// ✓
success = (msg?: string) => this.emit("success", msg);
// ✗: msg is a required argument
// → "Argument of type 'string | undefined' is not assignable to parameter of type 'string'."
}
Static Methods
let [body] = await EventEmitter.once(emitter, "message");
console.log(body.toLowerCase());
// ✓: type inference also works for static methods
for await(let e of EventEmitter.on(emitter, "success")){
let [s, a, b] = e;
console.log(s.length+a+b);
// ✗: a and b are optional parameters
// → "Object is possibly 'undefined'."
}