如何在打字稿中以安全的方式从 WindowEventMap 引用 dom 事件名称?
How can I reference dom event names from WindowEventMap in a safe way in typescript?
我想为调试创建一些 dom 事件侦听器,但我想知道是否可以通过引用 属性 名称来确保编译时名称正确在 WindowEventMap
。我目前有以下内容:
addEventListenersForDebug(
mediaElement,
"abort",
"canplay",
"canplaythrough",
"durationchange",
//...
)
我尝试直接引用属性(例如 WindowEventMap.abort
等),但是它不起作用,我看到错误 TS2693: 'WindowEventMap' only refers to a type, but is being used as a value here.
我的最佳方法是基于
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,
//...
)
这里有没有更惯用的东西来避免重新定义所有键的需要?
最后我只是用 addEventListenersForDebug()
的类型签名来强制执行此操作
function addEventListenersForDebug(
mediaElement: HTMLMediaElement,
...eventNames: (keyof HTMLMediaElementEventMap)[]
) {
// code to add listeners
}
我想为调试创建一些 dom 事件侦听器,但我想知道是否可以通过引用 属性 名称来确保编译时名称正确在 WindowEventMap
。我目前有以下内容:
addEventListenersForDebug(
mediaElement,
"abort",
"canplay",
"canplaythrough",
"durationchange",
//...
)
我尝试直接引用属性(例如 WindowEventMap.abort
等),但是它不起作用,我看到错误 TS2693: 'WindowEventMap' only refers to a type, but is being used as a value here.
我的最佳方法是基于
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,
//...
)
这里有没有更惯用的东西来避免重新定义所有键的需要?
最后我只是用 addEventListenersForDebug()
function addEventListenersForDebug(
mediaElement: HTMLMediaElement,
...eventNames: (keyof HTMLMediaElementEventMap)[]
) {
// code to add listeners
}