-1

I would like to create a number of dom event listeners for debug, but I was wondering if it's possible to make sure that the names are correct at compile time by referencing the property names in WindowEventMap. I currently have the following:

  addEventListenersForDebug(
    mediaElement,
    "abort",
    "canplay",
    "canplaythrough",
    "durationchange",
    //...
  )

I tried the referencing the properties directly (eg WindowEventMap.abort etc), but ofc it doesn't work and I see the error TS2693: 'WindowEventMap' only refers to a type, but is being used as a value here.

The best approach I have is based on How to get the property name / key name of an interface as a string in Typescript


  class WindowEventMapKeys {
    static readonly abort: keyof WindowEventMap = "abort";
    static readonly canplay: keyof WindowEventMap = "canplay";
    static readonly canplaythrough: keyof WindowEventMap = "canplaythrough";
    static readonly durationchange: keyof WindowEventMap = "durationchange";
  }

  addEventListenersForDebug(
    mediaElement,
    WindowEventMapKeys.abort,
    WindowEventMapKeys.canplay,
    WindowEventMapKeys.canplaythrough,
    WindowEventMapKeys.durationchange,
    //...
  )

Is there something more idiomatic here avoiding the need to redefine all the keys?

robd
  • 9,646
  • 5
  • 40
  • 59

1 Answers1

0

In the end I just enforced this with the type signature of addEventListenersForDebug()

  function addEventListenersForDebug(
    mediaElement: HTMLMediaElement,
    ...eventNames: (keyof HTMLMediaElementEventMap)[]
  ) {
    // code to add listeners
  }
robd
  • 9,646
  • 5
  • 40
  • 59