index.d.ts 1.3 KB

123456789101112131415161718192021
  1. export declare type EventType = string | symbol;
  2. export declare type Handler<T = unknown> = (event: T) => void;
  3. export declare type WildcardHandler<T = Record<string, unknown>> = (type: keyof T, event: T[keyof T]) => void;
  4. export declare type EventHandlerList<T = unknown> = Array<Handler<T>>;
  5. export declare type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>;
  6. export declare type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<keyof Events | '*', EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>>;
  7. export interface Emitter<Events extends Record<EventType, unknown>> {
  8. all: EventHandlerMap<Events>;
  9. on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
  10. on(type: '*', handler: WildcardHandler<Events>): void;
  11. off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void;
  12. off(type: '*', handler: WildcardHandler<Events>): void;
  13. emit<Key extends keyof Events>(type: Key, event: Events[Key]): void;
  14. emit<Key extends keyof Events>(type: undefined extends Events[Key] ? Key : never): void;
  15. }
  16. /**
  17. * Mitt: Tiny (~200b) functional event emitter / pubsub.
  18. * @name mitt
  19. * @returns {Mitt}
  20. */
  21. export default function mitt<Events extends Record<EventType, unknown>>(all?: EventHandlerMap<Events>): Emitter<Events>;