In my App component(simple one 😅), I have created a form with 3 input fields and 1 submit button. When the user fills the form and after clicking on submit button the form data is displayed on the page.
Now, my problem is that I am getting typescript error when accessing form elements node from event.target.elements.
TypeError: Property 'elements' does not exist on type 'EventTarget'.
I tried to solve this problem by typecasting the event.target as HTMLInputElement but the error still persists.
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const { firstName, lastName, company } = (event.target as HTMLInputElement).elements;
setFormData({
firstName: firstName.value,
lastName: lastName.value,
company: company.value
});
}
Error message when I used the above code
TypeError: Property 'elements' does not exist on type 'HTMLInputElement'.
Sandbox link
In order to type the event.target in forms, you need to do it manually, see forms and events TS cheatsheet.
interface FormData {
firstName: { value: string };
lastName: { value: string };
company: { value: number[] };
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const { firstName, lastName, company } = e.target as typeof e.target & FormData;
setFormData({
firstName: { value: firstName.value },
lastName: { value: lastName.value },
company: { value: company.value }
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With