CustomEvent Types The Detail Payload

Type the payload once with CustomEvent<T> so dispatch and listeners share the same detail shape, then destructure fields without manual checks.

TypescriptData Integrity

Code

typescriptsnippet
21 lines
// CustomEvent<T> types the payload passed through detail
type CartEvent = CustomEvent<{ sku: string; qty: number }>;

function publishCartAdded(sku: string, qty: number): void {
  const event: CartEvent = new CustomEvent('cart:added', {
    detail: { sku, qty },
  });
  window.dispatchEvent(event);
}

let lastSku = '';
window.addEventListener('cart:added', (event) => {
  // Listeners receive plain Event: one assertion restores the typed payload
  const { sku, qty } = (event as CartEvent).detail;
  lastSku = sku;
  console.log(`added ${qty} x ${sku}`);
});

publishCartAdded('tee-42', 2);
publishCartAdded('mug-7', 1);
console.log('last sku:', lastSku);

The mechanics

The operative surface is the function publishCartAdded — everything else is wiring.

Caveats

  • Only built-in APIs appear, leaving no supply chain to audit.
  • window exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Signature: function publishCartAdded(sku: string, qty: number)

The demo output is labeled (added $, last sku:); each label names the call that printed it.

Statements that matter

window.addEventListener('cart:added', (event) => {
  // Listeners receive plain Event: one assertion restores the typed payload
  const { sku, qty } = (event as CartEvent).detail;
  lastSku = sku;
  console.log(`added ${qty} x ${sku}`);
});

Interactive Tools for This Topic

FAQ

Does CustomEvent Types The Detail Payload run in plain Node.js?
No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.