Stronger typing (#114)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* improved typing * upd readme * upd readme * upd test & readme * removed magic 1 * removed ts-toolbelt dependency
authored by iyegoroff · committed by GitHub · parent 22c5dcb · Browse files · 7 files·+138 added−65 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+138 added−65 removed
- tests:+72 added−26 removed
- other:+66 added−39 removed
Provenance
- Commit
8f439b8- Tree
5796904- Author
iyegoroff <iegoroff@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
22c5dcb
7 files changed+138 added−65 removed
modified:src/index.ts+45 added-26 removed
12345656789101191012131415131617181920151621222318192425262122272829242530313233343536373833394041424344454647483 unmodified lines525354554556575859495060616263536465666768695970717273636474757677787980818272838474858687888990808182919293949596979899100101102103104export type EventType = string | symbol;
// An event handler can take an optional event argument// and should not return a valueexport type Handler<T = any> = (event?: T) => void;export type WildcardHandler = (type: EventType, event?: any) => void;export type Handler<T = unknown> = (event: T) => void;export type WildcardHandler<T = Record<string, unknown>> = ( type: keyof T, event: T[keyof T]) => void;
// An array of all currently registered event handlers for a typeexport type EventHandlerList = Array<Handler>;export type WildCardEventHandlerList = Array<WildcardHandler>;export type EventHandlerList<T = unknown> = Array<Handler<T>>;export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;
// A map of event types and their corresponding event handlers.export type EventHandlerMap = Map<EventType, EventHandlerList | WildCardEventHandlerList>;export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map< keyof Events | '*', EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>>;
export interface Emitter { all: EventHandlerMap;export interface Emitter<Events extends Record<EventType, unknown>> { all: EventHandlerMap<Events>;
on<T = any>(type: EventType, handler: Handler<T>): void; on(type: '*', handler: WildcardHandler): void; on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void; on(type: '*', handler: WildcardHandler<Events>): void;
off<T = any>(type: EventType, handler: Handler<T>): void; off(type: '*', handler: WildcardHandler): void; off<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void; off(type: '*', handler: WildcardHandler<Events>): void;
emit<T = any>(type: EventType, event?: T): void; emit(type: '*', event?: any): void; emit<Key extends keyof Events>(type: Key, event: Events[Key]): void; emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;}
/** * Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt * @returns {Mitt} */export default function mitt(all?: EventHandlerMap): Emitter {export default function mitt<Events extends Record<EventType, unknown>>( all?: EventHandlerMap<Events>): Emitter<Events> { type GenericEventHandler = | Handler<Events[keyof Events]> | WildcardHandler<Events>; all = all || new Map();
return {
3 unmodified lines all,
/** * Register an event handler for the given type. * @param {string|symbol} type Type of event to listen for, or `"*"` for all events * @param {string|symbol} type Type of event to listen for, or `'*'` for all events * @param {Function} handler Function to call in response to given event * @memberOf mitt */ on<T = any>(type: EventType, handler: Handler<T>) { const handlers = all.get(type); on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) { const handlers: Array<GenericEventHandler> | undefined = all!.get(type); const added = handlers && handlers.push(handler); if (!added) { all.set(type, [handler]); all!.set(type, [handler] as EventHandlerList<Events[keyof Events]>); } },
/** * Remove an event handler for the given type. * @param {string|symbol} type Type of event to unregister `handler` from, or `"*"` * @param {string|symbol} type Type of event to unregister `handler` from, or `'*'` * @param {Function} handler Handler function to remove * @memberOf mitt */ off<T = any>(type: EventType, handler: Handler<T>) { const handlers = all.get(type); off<Key extends keyof Events>(type: Key, handler: GenericEventHandler) { const handlers: Array<GenericEventHandler> | undefined = all!.get(type); if (handlers) { handlers.splice(handlers.indexOf(handler) >>> 0, 1); } },
/** * Invoke all handlers for the given type. * If present, `"*"` handlers are invoked after type-matched handlers. * If present, `'*'` handlers are invoked after type-matched handlers. * * Note: Manually firing "*" handlers is not supported. * Note: Manually firing '*' handlers is not supported. * * @param {string|symbol} type The event type to invoke * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler * @memberOf mitt */ emit<T = any>(type: EventType, evt: T) { ((all.get(type) || []) as EventHandlerList).slice().map((handler) => { handler(evt); }); ((all.get('*') || []) as WildCardEventHandlerList).slice().map((handler) => { handler(type, evt); }); emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) { ((all!.get(type) || []) as EventHandlerList<Events[keyof Events]>) .slice() .map((handler) => { handler(evt!); }); ((all!.get('*') || []) as WildCardEventHandlerList<Events>) .slice() .map((handler) => { handler(type, evt!); }); } };}modified:test/index_test.ts+17 added-6 removed
1-import mitt, { Emitter } from '..';1+import mitt, { Emitter, EventHandlerMap } from '..';2 import chai, { expect } from 'chai';3 import { spy } from 'sinon';4 import sinonChai from 'sinon-chai';5 chai.use(sinonChai);8 unmodified lines14 const map = new Map();15 const a = spy();16 const b = spy();17 map.set('foo', [a, b]);18- const events = mitt(map);18+ const events = mitt<{ foo: undefined }>(map);19 events.emit('foo');20 expect(a).to.have.been.calledOnce;21 expect(b).to.have.been.calledOnce;22 });23 });24 25 describe('mitt#', () => {26- let events, inst: Emitter;26+ const eventType = Symbol('eventType');27+ type Events = {28+ foo: unknown;29+ constructor: unknown;30+ FOO: unknown;31+ bar: unknown;32+ Bar: unknown;33+ 'baz:bat!': unknown;34+ 'baz:baT!': unknown;35+ Foo: unknown;36+ [eventType]: unknown;37+ };38+ let events: EventHandlerMap<Events>, inst: Emitter<Events>;39 28- beforeEach( () => {40+ beforeEach(() => {41 events = new Map();42 inst = mitt(events);43 });44 49 unmodified lines94 });95 96 it('can take symbols for event types', () => {97 const foo = () => {};86- const eventType = Symbol('eventType');98 inst.on(eventType, foo);99 expect(events.get(eventType)).to.deep.equal([foo]);100 });101 59 unmodified lines161 162 it('should invoke handler for type', () => {163 const event = { a: 'b' };164 154- inst.on('foo', (one, two?) => {165+ inst.on('foo', (one, two?: unknown) => {166 expect(one).to.deep.equal(event);167 expect(two).to.be.an('undefined');168 });169 32 unmodified linesmodified:test/test-types-compilation.ts+55 added-20 removed
12345567891011121314151617181920212282324251112262728293031151632333435363738394041204243442324454647484950272851525354555657585931603361626336373839404164656642676869707172737475767778/* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unused-vars */
import mitt from '..';
const emitter = mitt();interface SomeEventData { name: string;}
const emitter = mitt<{ foo: string; someEvent: SomeEventData; bar?: number;}>();
const barHandler = (x?: number) => {};const fooHandler = (x: string) => {};const wildcardHandler = ( _type: 'foo' | 'bar' | 'someEvent', _event: string | SomeEventData | number | undefined) => {};
/* * Check that if on is provided a generic, it only accepts handlers of that type * Check that 'on' args are inferred correctly */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {}; // @ts-expect-error emitter.on('foo', barHandler); emitter.on('foo', fooHandler);
emitter.on('bar', barHandler); // @ts-expect-error emitter.on<string>('foo', badHandler); emitter.on<string>('foo', goodHandler); emitter.on('bar', fooHandler);
emitter.on('*', wildcardHandler); // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string emitter.on('*', fooHandler); // @ts-expect-error emitter.on('*', barHandler);}
/* * Check that if off is provided a generic, it only accepts handlers of that type * Check that 'off' args are inferred correctly */{ const badHandler = (x: number) => {}; const goodHandler = (x: string) => {}; // @ts-expect-error emitter.off('foo', barHandler); emitter.off('foo', fooHandler);
emitter.off('bar', barHandler); // @ts-expect-error emitter.off<string>('foo', badHandler); emitter.off<string>('foo', goodHandler); emitter.off('bar', fooHandler);
emitter.off('*', wildcardHandler); // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string emitter.off('*', fooHandler); // @ts-expect-error emitter.off('*', barHandler);}
/* * Check that if emitt is provided a generic, it only accepts event data of that type * Check that 'emit' args are inferred correctly */{ interface SomeEventData { name: string; } // @ts-expect-error emitter.emit<SomeEventData>('foo', 'NOT VALID'); emitter.emit<SomeEventData>('foo', { name: 'jack' }); // @ts-expect-error emitter.emit('someEvent', 'NOT VALID'); emitter.emit('someEvent', { name: 'jack' });}
// @ts-expect-error emitter.emit('foo'); // @ts-expect-error emitter.emit('foo', 1); emitter.emit('foo', 'string');
emitter.emit('bar'); emitter.emit('bar', 1); // @ts-expect-error emitter.emit('bar', 'string');}modified:.gitignore+1 added
4 unmodified lines5 /index.d.ts6 package-lock.json7 .DS_Store8 .idea9+.vscodemodified:package.json+5 added-4 removed
10 unmodified lines11 "typings": "index.d.ts",12 "scripts": {13 "test": "npm-run-all --silent typecheck lint mocha test-types",14 "mocha": "mocha test",15- "test-types": "tsc test/test-types-compilation.ts --noEmit",15+ "test-types": "tsc test/test-types-compilation.ts --noEmit --strict",16 "lint": "eslint src test --ext ts --ext js",17 "typecheck": "tsc --noEmit",18 "bundle": "microbundle",19 "build": "npm-run-all --silent clean -p bundle -s docs",57 unmodified lines77 "jest/valid-expect": 0,78 "@typescript-eslint/no-explicit-any": 0,79 "@typescript-eslint/explicit-function-return-type": 0,80 "@typescript-eslint/explicit-module-boundary-types": 0,81- "@typescript-eslint/no-empty-function": 081+ "@typescript-eslint/no-empty-function": 0,82+ "@typescript-eslint/no-non-null-assertion": 083 }84 },85 "eslintIgnore": [86 "dist",17 unmodified lines104 "rimraf": "^3.0.2",105 "sinon": "^9.0.2",106 "sinon-chai": "^3.5.0",107 "ts-node": "^8.10.2",107- "typescript": "^3.9.3"108+ "typescript": "^3.9.7"109 }109-}110+}modified:README.md+13 added-5 removed
78 unmodified lines79 ```80 81 ### Typescript82 83+Set `"strict": true` in your tsconfig.json to get improved type inference for `mitt` instance methods.84+85 ```ts86 import mitt from 'mitt';87+88+type Events = {89+ foo: string90+ bar?: number91+}92+85-const emitter: mitt.Emitter = mitt();93+const emitter: mitt.Emitter<Events> = mitt<Events>();94 ```95 96 ## Examples & Demos97 35 unmodified lines133 Register an event handler for the given type.134 135 #### Parameters136 129-- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `"*"` for all events137+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `'*'` for all events138 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event139 140 ### off141 142 Remove an event handler for the given type.143 144 #### Parameters145 138-- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `"*"`146+- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to unregister `handler` from, or `'*'`147 - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Handler function to remove148 149 ### emit150 151 Invoke all handlers for the given type.144-If present, `"*"` handlers are invoked after type-matched handlers.152+If present, `'*'` handlers are invoked after type-matched handlers.153 146-Note: Manually firing "\*" handlers is not supported.154+Note: Manually firing '\*' handlers is not supported.155 156 #### Parameters157 158 - `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** The event type to invoke29 unmodified linesmodified:tsconfig.json+2 added-4 removed
12345678991011121011{ "compileOnSave": false, "compilerOptions": { "strict": true, "noEmit": true, "declaration": true, "moduleResolution": "node", "esModuleInterop": true }, "include": [ "src/*.ts", "test/*.ts", ] "include": ["src/*.ts", "test/*.ts"]}