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.
Code
// 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.
windowexist 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.