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.

TypescriptData Integrity

Code

typescriptsnippet
21 lines
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: document are 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

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.