From 796f1ec671a13b01c44527ea6550b4e53cf98844 Mon Sep 17 00:00:00 2001 From: Ultroncn <82553854+Ultroncn@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:25:41 +0000 Subject: [PATCH] fix(types): allow interfaces as event maps (fixes #209) Interfaces have no implicit index signature, so they did not satisfy the `Record` constraint on the Events type parameter (TS2344). Relax the constraint to `object`: type aliases and interfaces are both accepted, while primitives such as string and number are still rejected. Adds an interface case to the type-compilation tests and notes in the README that either `type` or `interface` works. --- README.md | 2 ++ src/index.ts | 6 +++--- test/test-types-compilation.ts | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0219f3a..a139ce2 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,8 @@ emitter.on('foo', (e) => {}); // 'e' has inferred type 'string' emitter.emit('foo', 42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'. (2345) ``` +Event maps can be declared with either `type` or `interface`. + Alternatively, you can use the provided `Emitter` type: ```ts diff --git a/src/index.ts b/src/index.ts index 17672aa..38e6db4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,12 +15,12 @@ export type WildCardEventHandlerList> = Array< >; // A map of event types and their corresponding event handlers. -export type EventHandlerMap> = Map< +export type EventHandlerMap = Map< keyof Events | '*', EventHandlerList | WildCardEventHandlerList >; -export interface Emitter> { +export interface Emitter { all: EventHandlerMap; on(type: Key, handler: Handler): void; @@ -43,7 +43,7 @@ export interface Emitter> { * @name mitt * @returns {Mitt} */ -export default function mitt>( +export default function mitt( all?: EventHandlerMap ): Emitter { type GenericEventHandler = diff --git a/test/test-types-compilation.ts b/test/test-types-compilation.ts index 476e631..14ac722 100644 --- a/test/test-types-compilation.ts +++ b/test/test-types-compilation.ts @@ -19,6 +19,23 @@ const wildcardHandler = ( _event: string | SomeEventData | number | undefined ) => {}; +/* + * Check that event maps declared as interfaces work too (#209). + * Interfaces have no implicit index signature, so they did not satisfy + * the old `Record` constraint. + */ +interface InterfaceEvents { + foo: string; + bar?: number; +} + +const interfaceEmitter = mitt(); +interfaceEmitter.on('foo', fooHandler); +interfaceEmitter.emit('foo', 'string'); +interfaceEmitter.emit('bar', 1); +// @ts-expect-error +interfaceEmitter.emit('foo', 1); + /* * Check that 'on' args are inferred correctly */