Skip to content
tezvyn:
Menu

Typed Custom Events: Making Browser Events Type-Safe

Source: developer.mozilla.orgHardHow cards are made

Typed Custom Events: Making Browser Events Type-Safe

CustomEvent lets you fire your own browser events, but its payload is any. Typing them means defining a specific shape for the event's detail property, turning a generic signal into a predictable, self-documenting API for your components.

Why it exists

Browser events like 'click' are powerful for decoupling. For application-specific logic, we need our own events. The browser's CustomEvent API provides this, but its detail property, which holds the data payload, is untyped (any) by default. This creates a hole in a TypeScript application's type safety, forcing developers to guess the shape of event data.

The mental model

A typed CustomEvent is a contract. You're telling the rest of your application, "An event named 'order-submitted' will be fired, and when it is, its detail property will ALWAYS contain an object with an orderId (string) and amount (number)." This turns a generic mechanism into a predictable, self-documenting API that your tools can understand.

How it works

You use TypeScript generics. The standard CustomEvent interface can be parameterized with the type of its detail property: CustomEvent<T>. When creating an event, you instantiate it as new CustomEvent<MyPayload>('event-name', { detail: myPayload }). When listening for the event, you must cast the received event object to your specific type to access the payload safely: (event as CustomEvent<MyPayload>).detail. This gives you full type-checking and autocomplete on the payload within your listener's scope.

When to use it

Use typed custom events for communication between loosely coupled parts of your application. This is common in micro-frontend architectures, when integrating vanilla JS components into a typed framework, or for creating a public API for a reusable component. For example, a date picker component could fire a date-selected event with a Date object in its detail, and the consuming application knows exactly what to expect.

When not to use it

Avoid using events for communication between tightly coupled components that can share state via props, context, or a state management library like Redux or Zustand. Event-based communication is powerful but can be harder to trace than direct state updates. If two components have a clear parent-child relationship, passing props is simpler and more explicit.

One canonical example

To signal a user login, first define the payload type: type UserLoginPayload = { userId: string; timestamp: number; }. Then, dispatch the event: const loginEvent = new CustomEvent<UserLoginPayload>('user:login', { detail: { userId: 'abc-123', timestamp: Date.now() } }); document.dispatchEvent(loginEvent);. A listener would then cast the event to read the detail: document.addEventListener('user:login', (e) => { const event = e as CustomEvent<UserLoginPayload>; console.log('User logged in:', event.detail.userId); });. The type assertion is the key to safety.

Interview question

What is the main advantage of using typed Custom Events in a TypeScript application?

  • a.It ensures the detail property's data structure is known and validated at compile-time.Correct
  • b.It allows for direct state sharing between tightly coupled components without props or context.
  • c.It eliminates the need for document.dispatchEvent by providing a dedicated event bus.
  • d.It automatically infers the type of the detail property when listening, removing the need for type assertions.
Why?

The card states that typed Custom Events create a 'contract' for the detail property, providing 'full type-checking and autocomplete' and a 'predictable, self-documenting API.' Option D is incorrect because the card explicitly mentions that you 'must cast the received event object' when listening.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.

See open roles