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

Why Does This Happen?

By default, an event target has the EventTarget type, which lacks certain properties (such as value) that you may expect to find on a standard HTML <input>, <button> or <textarea> element. For example:

elem.addEventListener('click', function (e) {
  // Property 'value' does not exist on type 'EventTarget'.
  console.log(e.target.value);
}, false);

This leads to a compiler error because TypeScript cannot verify the existence of the value property on the EventTarget type as this property is exclusively available on elements such as HTMLInputElement, HTMLButtonElement, and HTMLTextAreaElement.

How to Fix the Issue?

To fix this issue, you can specify the correct type for the event target. Assuming that the event target is one of; HTMLInputElement, HTMLButtonElement, or HTMLTextAreaElement, you can fix this error in the following ways:

  1. Using Type Assertion

    elem.addEventListener('click', (e) {
      // Property 'value' does not exist on type 'EventTarget'.
      e.target.value;
    
      // possible fixes:
      (e.target as HTMLInputElement).value;
      (e.target as HTMLButtonElement).value;
      (e.target as HTMLTextAreaElement).value;
      // etc.
    }, false);
    
  2. Using Type Guard

    elem.addEventListener('click', (e) {
      // Property 'value' does not exist on type 'EventTarget'.
      e.target.value;
    
      // possible fixes:
      if (e.target instanceof HTMLInputElement) {
        e.target.value;
      }
    
      if (e.target instanceof HTMLButtonElement) {
        e.target.value;
      }
    
      if (e.target instanceof HTMLTextAreaElement) {
        e.target.value;
      }
    }, false);
    

    Using a type guard also provides type safety on runtime, where the target element can possibly be null or of a different type.

When specifying a type for your event target, it's important to select the most suitable type for your particular use case. You can identify the appropriate type for your HTML element by going through the list of Web API interfaces. This ensures that your TypeScript code accurately reflects the properties and methods available on the specific HTML element you're working with.

Further Reading


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.