Type-safe event emitter pattern
📖 Scenario: You are building a simple event system for a chat app. Different parts of the app listen to events like new messages or user status changes. You want to make sure the events and their data are always the right type to avoid bugs.
🎯 Goal: Create a type-safe event emitter in TypeScript that only allows specific events with correct data types. Then use it to listen and emit events safely.
📋 What You'll Learn
Create an interface called
ChatEvents with two events: message and userStatusDefine
message event data as an object with from (string) and text (string)Define
userStatus event data as an object with user (string) and online (boolean)Create a generic
EventEmitter class that uses the ChatEvents interface for type safetyAdd
on and emit methods to EventEmitter that enforce event names and data typesUse the
EventEmitter to listen for message and userStatus events and print their data💡 Why This Matters
🌍 Real World
Event emitters are used in apps to handle things like user actions, data updates, or notifications in a clean way.
💼 Career
Understanding type-safe event emitters helps you build reliable, maintainable code in TypeScript, a skill valued in frontend and backend development.
Progress0 / 4 steps