How to Fix "Property 'value' does not exist on type 'EventTarget'" Error in TypeScript


How can we fix the Property 'value' does not exist on type 'EventTarget' error in TypeScript?

Suppose we have an event handler that takes a ChangeEvent as a parameter.

const handler = (e: ChangeEvent) => {
  const value = e.target.value;
}

Let’s say we have an <input> element calling this handler function.

<input onChange={handler} /> 

However, running this in a TypeScript environment throws this error:

Property 'value' does not exist on type 'EventTarget'

How can we fix this error?

The solution below is specifically for EventTarget errors. Unfortunately, there are many other common “Property does not exist” errors in TypeScript.

Cast target to HTMLElement

In order to avoid this error, we’ll need to cast our event target to a specific HTMLElement interface.

In the example above, we’re using an <input> element, so we’ll cast the generic e.target to HTMLInputElement.

If it’s a <textarea> element, we’ll cast to HTMLTextAreaElement.

Check out the list of HTMLElement interfaces on the Mozilla docs.

const handler = (e: ChangeEvent) => {
  const value = (e.target as HTMLInputElement).value;
}

Cast to HTMLElement in the parameter

We can avoid the cast in the function body by casting the parameter.

const handler = (e: ChangeEvent<HTMLInputElement>) => {
  const value = e.target.value;
}

A clean approach would be to destructure the parameter and cast accordingly.

const handler = (e: { target: HTMLInputElement }) => {
  const value = e.target.value;
}

The only issue with the above approach is that we can only access the target element of event.

If we want to access other properties of event, we can use the previous approach.