
Building a Type-Safe Event Bus in TypeScript: Decouple Your Microservices
Building a Type-Safe Event Bus in TypeScript: Decouple Your Microservices Your payment service calls notification directly. One change breaks three services. An event bus decouples producers from consumers. The Problem Untyped events break at runtime. Typos compile fine but crash in production. Event Map interface EventMap { " user.created " : { id : string ; email : string ; name : string }; " user.deleted " : { id : string }; " order.placed " : { orderId : string ; userId : string ; total : number }; " payment.completed " : { orderId : string ; amount : number ; currency : string }; } The Type-Safe Event Bus type Handler < T > = ( payload : T ) => void | Promise < void > ; class EventBus < E extends Record < string , unknown >> { private handlers = new Map (); on ( event , handler ) { if ( \ ! this . handlers . has ( event )) this . handlers . set ( event , new Set ()); this . handlers . get ( event ). add ( handler ); return () => this . handlers . get ( event ). delete ( handler );
Continue reading on Dev.to Webdev
Opens in a new tab



