Contextual Typing Is Lost When Handlers Are Extracted
Inline handlers get parameter types from context; extracting one into a variable loses that context, leaving an implicit any until you annotate it.
Code
const form = document.querySelector('form') as HTMLFormElement;
// Inline arrow: contextual typing gives event the SubmitEvent type for free.
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('inline handler knows SubmitEvent without annotations');
});
// Extracted to a variable first: contextual typing is lost and the
// standalone parameter becomes an implicit any, so this line no longer compiles.
// @ts-expect-error — a standalone arrow gets no contextual type
const looseHandler = (event) => event.preventDefault();
// Fix: annotate the variable with the expected signature.
const submitHandler: (event: SubmitEvent) => void = (event) => {
event.preventDefault();
console.log('annotated handler is reusable and still type-safe');
};
form.addEventListener('submit', submitHandler);
console.log(typeof looseHandler === 'function');The mechanics of this demo — Contextual Typing Is Lost When Handlers Are Extracted
Everything happens inside the function looseHandler.
What to watch for
- No dependencies section needed; the standard library is the whole story.
- A browser is the runtime here:
documentare not available in Node.
Using it
The signature everything hangs on: const looseHandler = (event)
Key statements
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('inline handler knows SubmitEvent without annotations');
});
const submitHandler: (event: SubmitEvent) => void = (event) => {
event.preventDefault();
console.log('annotated handler is reusable and still type-safe');
};
const looseHandler = (event) => event.preventDefault();
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 Contextual Typing Is Lost When Handlers Are Extracted run in plain Node.js?
- No — it touches `document`, 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.