typescriptsvelte

Svelte form on:submit type TypeScript


I am trying to build a simple form in Svelte TypeScript.

My on:submit looks like this: <form on:submit={onSubmit}>, and my onSubmit function is defined as:

const onSubmit = (event: HTMLFormElement) => {
    event.preventDefault();
    dispatch("addPerson", person);
    person = {
      name: "",
      isOwed: 0,
    };
  };

With this code I get the TypeScript problem:

Type '(event: HTMLFormElement) => void' is not assignable to type 'EventHandler<Event, HTMLFormElement>'. Types of parameters 'event' and 'event' are incompatible.

I get that the event passed to onSubmit has the type EventHandler<Event, HTMLFormElement>, and that my function is only expecting HTMLFormElement, but I can't manage to expect the whole EventHandler object. How can I achieve this?


Solution

  • The event type is a SubmitEvent.

    function handleSubmit(e: SubmitEvent) {
     const formData = new FormData(e.target as HTMLFormElement)
    }
    
    <form on:submit|preventDefault={handleSubmit}>