我想创建一些用于调试的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.
我拥有的最好的方法是基于如何在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,
//...
)
这里有没有更惯用的方法可以避免重新定义所有密钥?
最后,我只是用addEventListenersForDebug()
的类型签名强制执行了这一点
function addEventListenersForDebug(
mediaElement: HTMLMediaElement,
...eventNames: (keyof HTMLMediaElementEventMap)[]
) {
// code to add listeners
}