
Type-Safe CustomEvents: Better Messaging with Native APIs
The native EventTarget is a hidden gem for internal messaging. It is built-in, fast and stays out of your way. However, the standard CustomEvent interface is a bit of a "black box" for TypeScript. Usually, you end up casting e as CustomEvent<MyData> every time you want to access your data. We can do better. By wrapping the target and the event creation, we can have a completely type-safe event bus with zero runtime overhead. The Problem When you dispatch a CustomEvent , the data is tucked away in the detail property. Out of the box, addEventListener has no idea what that detail contains, forcing you to manually type your listeners. The Solution: TypedEventTarget We can use a generic map to link event names to their specific CustomEvent payloads. type EventListener < E extends Event > = ( evt : E ) => void ; interface EventListenerObject < E extends Event > { handleEvent ( evt : CustomEvent < E > ): void ; } // The type of our listener receives the CustomEvent with our specific data typ
Continue reading on Dev.to Webdev
Opens in a new tab




