Type error: Property 'currentTime' does not exist on type 'EventTarget & HTMLInputElement'

Type error: Property 'currentTime' does not exist on type 'EventTarget & HTMLInputElement'

我目前正在 nextJS 项目中使用 TypeScript。 我正在异步使用 cdn 版本的 flowplayer,它用新属性扩展了 event.target。

问题是当我尝试构建时出现错误: 类型错误:属性 'currentTime' 在类型 'EventTarget & HTMLInputElement' 上不存在。

我需要将它与这些属性相交:currentTime、duration、opts。 这是我尝试做的:

type FlowPlayerEvent<T extends EventTarget> = Event & {
target: T;
currentTime: Number;
duration: Number;
opts: Object;
};

这是我的事件处理程序

function stateHandler(ev : Event) {
const Event: FlowPlayerEvent = ev.target;
if (ev.type === 'pause') { console.log('paused'); }
if (ev.type === 'playing') { console.log(`Playing at ${Event.currentTime}, duration is: ${Event.duration}, video ID is: ${Event.opts.metadata.id}`); }
if (ev.type === 'timeupdate') { console.log(Event.currentTime); }
if (ev.type === 'ended') { console.log('The end'); }

}

当我将鼠标悬停在 FlowPlayerEvent 上时,这就是我得到的: 通用类型 'FlowPlayerEvent' 需要 1 个类型参数 (s).ts(2314)

在这种情况下,正确的扩展方法是什么?

提前致谢!

您对事件事件目标感到困惑。 currentTimeduration 属性存在于目标元素上,而不是事件上。这些都是原生 HTMLVideoElement 的属性。 opts 似乎是由 flowplayer 添加的,所以 tp 类型更难。

我不熟悉 flowplayer,所以我不得不看看 the docs。我不确定这个包是否已经存在打字稿类型。对于您在这里使用的属性,这应该有效:

type FlowPlayerElement = HTMLVideoElement & {
    opts: {
        metadata: {
            id: string;
        }
    }
}

type FlowPlayerEvent = Event & {
    target: FlowPlayerElement;
};
function stateHandler(ev: FlowPlayerEvent) {
    const target = ev.target;
    if (ev.type === 'pause') { console.log('pausado'); }
    if (ev.type === 'playing') { console.log(`Tocando em ${target.currentTime} e a duração é: ${target.duration} e o id do vídeo: ${target.opts.metadata.id}`); }
    if (ev.type === 'timeupdate') { console.log(target.currentTime); }
    if (ev.type === 'ended') { console.log('Fim'); }
}

What's the correct way to extend it in this case?

const Event: FlowPlayerEvent<MyType> = ev.target;

所以你必须传入一个类型参数。

试试这个

function stateHandler(ev: React.ChangeEvent<HTMLVideoElement>) {
    const target = ev.target;
    if (ev.type === 'pause') { console.log('pausado'); }
    if (ev.type === 'playing') { console.log(`Tocando em ${target.currentTime} e a duração é: ${target.duration} e o id do vídeo: ${target.opts.metadata.id}`); }
    if (ev.type === 'timeupdate') { console.log(target.currentTime); }
    if (ev.type === 'ended') { console.log('Fim'); }
}