【问题标题】:Type error: Property 'currentTime' does not exist on type 'EventTarget & HTMLInputElement'类型错误:“EventTarget & HTMLInputElement”类型上不存在属性“currentTime”
【发布时间】:2021-07-04 12:32:54
【问题描述】:

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

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

我需要将它与以下属性相交: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。它有打字稿类型吗?目标应该是HTMLVideoElement 还是其他?

标签: typescript next.js flowplayer


【解决方案1】:

试试这个

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

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    您对 事件事件目标 感到困惑。 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'); }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2016-09-14
      • 2019-01-28
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多