HTMLAudioElement as JS Audio

Viewed 120

I have an audio that I load using HTML:

<audio>
    <source src="file.ogg" />
    <source src="file.mp3" />
</audio>

I have also extended the prototype to create a new function:

Audio.prototype.restart = function(){
    this.pause();
    this.currentTime = 0;
    this.play();
}

However, when I fetch the audio element, typescript does not recognize it as an instance of Audio:

let file = document.querySelector("audio")! as Audio;

file.restart()

I get two errors:

'Audio' refers to a value, but is being used as a type here. Did you mean 'typeof Audio'?ts(2749)

Property 'restart' does not exist on type 'HTMLAudioElement'.ts(2339)

How do I fix this?

1 Answers

You need to

  • Tell TS that a restart function now exists on HTMLAudioElements
  • Tell TS that the querySelector('audio') will return an HTMLAudioElement, which can be done with generics
interface HTMLAudioElement {
    restart: () => void;
}
Audio.prototype.restart = function(){
    this.pause();
    this.currentTime = 0;
    this.play();
}
let file = document.querySelector<HTMLAudioElement>("audio")!;

file.restart()

'Audio' refers to a value, but is being used as a type here.

comes up because Audio is a constructor - a value.

console.log(typeof Audio);

Related