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

#Why Does This Happen?

The files property exists on the HTMLInputElement interface and not on the EventTarget object (which is the default type for an event target). Therefore, when you try to access the files property on an event target, TypeScript complains:

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

The reason for this is that TypeScript cannot verify the existence of the files property on the EventTarget interface as this property is exclusively available on the HTMLInputElement interface (specifically, when using the <input type="file"> HTML element).

#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 <input type="file">, you can fix this error in either of the following ways:

  1. Using Type Assertion

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

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

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

These solutions help TypeScript understand that the event target is indeed an HTMLInputElement, and it allows you to access the "files" property without triggering a type error.

#Further Reading


This post was published 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.