SubmitEvent Types Form Handlers

addEventListener("submit") infers SubmitEvent in TypeScript, so submitter and preventDefault arrive typed instead of as a loose Event parameter.

TypescriptForm Validation

Code

typescriptsnippet
15 lines
const form = document.querySelector<HTMLFormElement>('#signup');

if (form) {
  // submit 监听的 event 被推断为 SubmitEvent,而不是宽泛的 Event
  form.addEventListener('submit', (event) => {
    event.preventDefault();

    // event.submitter 是触发提交的按钮,同样被正确推断
    const data = new FormData(form);
    const email = String(data.get('email') ?? '');

    console.log('submitter:', event.submitter?.id ?? 'none');
    console.log('email:', email);
  });
}

How the snippet works

Top-level bindings form hold the demo state — nothing sits inside a function scope.

Watch out for

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Output lines are prefixed (submitter:, email:), making each step’s effect easy to spot.

Statements that matter

form.addEventListener('submit', (event) => {
  event.preventDefault();
  // event.submitter 是触发提交的按钮,同样被正确推断
  const data = new FormData(form);
  const email = String(data.get('email') ?? '');
  console.log('submitter:', event.submitter?.id ?? 'none');
  console.log('email:', email);
});

Interactive Tools for This Topic

FAQ

Does SubmitEvent Types Form Handlers 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.