Svelte form on:submit type TypeScript

Viewed 1307

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?

2 Answers

The event type is a SubmitEvent.

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

The event parameter is an Event, not a HTMLFormElement HTML node. So you can replace event: HTMLFormElement to event: Event or even better (as suggested by TypeScript): event: EventHandler<Event, HTMLFormElement>.

Related