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

Why Does This Happen?

The controls property exists on the HTMLMediaElement, and not on the EventTarget object (which is the default type for an event target). This means that when you try to access the controls property on an event target, TypeScript will complain:

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

This is because TypeScript cannot verify the existence of the controls property on the EventTarget type as this property is exclusively available on elements of type HTMLMediaElement, and its subsets; HTMLVideoElement and HTMLAudioElement.

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 an HTML media element (i.e. one of, <audio> or <video> elements), you can fix this error in either of the following ways:

  1. Using Type Assertion

    elem.addEventListener('click', (e) {
      // Property 'controls' does not exist on type 'EventTarget'.
      e.target.controls;
    
      // possible fixes:
      (e.target as HTMLMediaElement).controls;
      (e.target as HTMLVideoElement).controls;
      (e.target as HTMLAudioElement).controls;
    }, false);
    
  2. Using Type Guard

    elem.addEventListener('click', (e) {
      // Property 'controls' does not exist on type 'EventTarget'.
      e.target.controls;
    
      // possible fix:
      const isMediaElem = e.target instanceof HTMLMediaElement; // or `HTMLVideoElement` or `HTMLAudioElement`
    
      if (isMediaElem) {
        e.target.controls;
      }
    }, 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 HTMLMediaElement (or its subsets, HTMLVideoElement and HTMLAudioElement), and it allows you to access the "controls" 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.