A tiny, strongly-typed event handler system in TypeScript for building modular and extensible hook/event pipelines.
npm install @mappia/whook``bash`
npm install @mappia/whook
@mappia/whook allows you to define events with a discriminated union type, register event-specific handlers, and then combine them into a single dispatcher that can invoke all relevant handlers for an event.
`ts`
type MyEvents =
| { type: 'user.created'; id: string }
| { type: 'order.placed'; orderId: number };
2. Create the system
`ts
import { createEventHandlerSystem } from '@mappia/whook';
const { on, combineHandlers } = createEventHandlerSystem
`
3. Register handlers
`ts
const userCreated = on('user.created', async (event) => {
console.log('New user ID:', event.id);
});
const orderPlaced = on('order.placed', async (event) => {
console.log('Order ID:', event.orderId);
});
`
4.
`ts
const dispatch = combineHandlers(userCreated, orderPlaced);
await dispatch('user.created', { type: 'user.created', id: 'abc123' });
await dispatch('order.placed', { type: 'order.placed', orderId: 42 });
`
If you try to register a handler for an unknown event type or handle the wrong payload, TypeScript will catch it:
`ts``
// ❌ TypeScript error
on('unknown.event', async (e) => {});