score:1

Accepted answer

you can use react.formevent as the type of the event parameter:

import react, { formevent } from "react";

// ...

const handlesubmit = (event: formevent) => {
    event.preventdefault();
    // ...
};

react has its own synthetic event types for the various events, which you use when setting up the handler the way you are, with an onxyz property on the element. (when setting up a handler via addeventlistener, which is still sometimes necessary, it's important not to use react's synthetic event types, since you're not setting up a react event handler, you're setting up a dom event handler. but with the way you're doing it, you want the synthetic type.)

you could type the function itself as a formeventhandler<htmlformelement>:

import react, { formevent } from "react";

// ...

const handlesubmit: formeventhandler = (event) => {
    event.preventdefault();
    // ...
};

note that both formevent and formeventhandler are generic types, accepting a type argument for the type of element that target will be. the default is element, which is often sufficient, but you could also supply htmlformelement (e.g., formevent<htmlformelement>) if you wanted to be more thorough.

score:0

you can assign a type to either to the function itself or to the arguments of the function, which is the event.


react.formeventhandler<htmlformelement>

this is the type for the function. if you use it like this:

handlesubmit: react.formeventhandler<htmlformelement> = e => {
}

then the type for the variable e will be inferred as react.formevent automatically. so you don't actually need to know the event type because you can apply a type to the function itself and get the correct type.


or you can assign the type to the event argument e.

handlesubmit = (e: react.formevent<htmlformelement>) => {
}

now the type for the handlesubmit property is inferred as (e: react.formevent<htmlformelement>) => void.


Related Query

More Query from same tag