TypeScript issue: Property ‘value’ does not exist on type ‘EventTarget’

Updated: January 8, 2024 By: Guest Contributor Post a comment

Overview

If you’ve been working with TypeScript and HTML event handling, you might have encountered the error: ‘Property ‘value’ does not exist on type ‘EventTarget’.’ This usually occurs during the development of web applications when developers are trying to access the value of an HTML form element within an event handler. TypeScript, being a statically typed language, enforces type safety and does not allow you to directly manipulate the DOM without proper type assertion. In this tutorial, we’re going to explore several solutions to resolve this issue effectively.

Solution 1: Type Casting with ‘as’ keyword

Steps:

  1. Type cast the target element to the specific HTML element type using the ‘as’ keyword.
  2. Access the ‘value’ property of the casted type.

Code example:

const handleInput = (event: Event) => {
 const target = event.target as HTMLInputElement;
 console.log(target.value);
};

Solution 2: Type Guard Function

Steps:

  1. Create a type guard function that checks if the event target is an instance of the HTMLInputElement.
  2. Use the type guard in the event handler before accessing the ‘value’ property.

Code example:

function isInputEvent(event: Event): event is Event & { target: HTMLInputElement } {
 return event.target instanceof HTMLInputElement;
}

const handleInput = (event: Event) => {
 if (isInputEvent(event)) {
 console.log(event.target.value);
 }
};

Solution 3: HTMLElement Interface

Steps:

  1. Explicitly specify the element type in the event parameter using the generic syntax.
  2. Access the ‘value’ directly from the event target.

Code example:

const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
 console.log(event.target.value);
};

Final Words

Each of these solutions has its own advantages and limitations. Using the ‘as’ keyword is the quickest method but doesn’t provide any runtime type safety. The type guard function adds a level of security, ensuring that the target meets certain conditions before its properties are accessed. However, it adds verbosity to the code. The generic event type approach ties the event handling explicitly to a particular element type, which makes it clear but can be restrictive if multiple input types are expected.