0
votes

I am currently using TypeScript in a nextJS project. I am using a cdn version of flowplayer asynchronously, and it extends the event.target with new attributes.

The problem is when I try to build I get the error: Type error: Property 'currentTime' does not exist on type 'EventTarget & HTMLInputElement'.

I need to intersect it with these attributes: currentTime, duration, opts. This is what I tried doing:

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

This is my event handler

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

}

When I hover over FlowPlayerEvent this is what I get: Generic type 'FlowPlayerEvent' requires 1 type argument(s).ts(2314)

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

Thanks in advance!

2
const Event: FlowPlayerEvent = ev.target; You seem confused about what is the event and what is the target. I'm not familiar with flowplayer. Does it have typescript types? Is the target supposed to be an HTMLVideoElement or something else?Linda Paiste

2 Answers

1
votes

You are getting confused between the event and the event target. The currentTime and duration properties exist on the target element, not the event. These are both properties of the native HTMLVideoElement. opts seems to be added by flowplayer so that's harder tp type.

I'm not familiar with flowplayer so I am having to look at the docs. I'm not sure if typescript types already exist for this package. For just the properties that you are using right here, this should work:

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
votes

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

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

So you have to pass in a type argument.