Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'elements' does not exist on type 'EventTarget' in React Typescript

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

like image 700
Subrato Pattanaik Avatar asked Nov 04 '25 11:11

Subrato Pattanaik


1 Answers

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 }
  });
}

Edit Type e.target

like image 178
Dennis Vash Avatar answered Nov 06 '25 02:11

Dennis Vash