类型错误:类型“EventTarget & HTMLInputElement”上不存在属性“currentTime”。

3

目前我正在一个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个类型参数。ts(2314)

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

提前感谢!


const Event: FlowPlayerEvent = ev.target; 你似乎对于事件和目标不太清楚。我对FlowPlayer不是很熟悉,它是否有typescript类型?目标应该是HTMLVideoElement还是其他什么东西? - Linda Paiste
3个回答

2
你混淆了“事件”和“事件目标”。`currentTime`和`duration`属性存在于目标元素上,而不是事件上。这两个属性都是原生`HTMLVideoElement`的属性。`opts`似乎是由flowplayer添加的,所以类型更难确定。
我不熟悉flowplayer,所以我需要查看{{link1:文档}}。我不确定这个包是否已经存在typescript类型。对于你在这里使用的属性,应该可以这样写:
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'); }
}

0

试试这个替代方案

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'); }
}

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0
在这种情况下,扩展它的正确方法是什么?
const Event: FlowPlayerEvent<MyType> = ev.target;

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接