I'm trying to get the values from a form
into FormData
:
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const value = formData.get('origin') ? 'open' : 'on';
updateResizingOptionsQuery.mutate({ value });
};
Since React sends SynteticEvents
, the interface of e.target
does not fit the FormData
constructor. In the example, I'm casting the type which is not ideal. What would be a better version of that code?
Without casting this lint error is thrown:
Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'. Type 'EventTarget' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, autoplete, elements, and 297 more.
I'm trying to get the values from a form
into FormData
:
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const value = formData.get('origin') ? 'open' : 'on';
updateResizingOptionsQuery.mutate({ value });
};
Since React sends SynteticEvents
, the interface of e.target
does not fit the FormData
constructor. In the example, I'm casting the type which is not ideal. What would be a better version of that code?
Without casting this lint error is thrown:
Share Improve this question edited Jan 30, 2023 at 22:18 Youssouf Oumar 46.3k16 gold badges101 silver badges104 bronze badges asked Jan 30, 2023 at 13:59 Xen_marXen_mar 9,75219 gold badges59 silver badges103 bronze badges 0Argument of type 'EventTarget' is not assignable to parameter of type 'HTMLFormElement'. Type 'EventTarget' is missing the following properties from type 'HTMLFormElement': acceptCharset, action, autoplete, elements, and 297 more.
1 Answer
Reset to default 11Using e.currentTarget
instead of e.target
works. Because currentTarget
always refers to the root event listener element, TypeScript knows it's the <form>
:
import { FormEvent } from "react";
export default function App() {
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const value = formData.get("origin") ? "open" : "on";
updateResizingOptionsQuery.mutate({ value });
};
return (
<div className="App">
<form onSubmit={handleSubmit}></form>
</div>
);
}