Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript "Property does not exists on type Element"

I'm starting my journey with Typescript. So I have video tag in my Html and in .ts file these lines:

...
class KomakhaPlayer {
  private container = ...;
  private video: Element = this.container.getElementsByClassName( 'video' )[ 0 ];
  private controls = ...;

  constructor(){
    this.video.controls = false; // ts error
    ...
  }
}
...

As you can see this.video has Element type, but below this.video.controls throws me a Typescript error Property 'controls' does not exists on type 'Element'.

Temporary I changed Element type to any, but I want to know how properly solve this error and handle similar in future. Thanks in advance!

SOLUTION: So the right approach is defining like this:

private video: HTMLVideoElement = <HTMLVideoElement>this.container.getElementsByClassName( 'video' )[ 0 ];

Explanation by @deceze below in comments

like image 759
lomboboo Avatar asked Mar 16 '17 14:03

lomboboo


1 Answers

Element is a very generic root object which indeed does not have a controls attribute. See https://developer.mozilla.org/en-US/docs/Web/API/Element. What you're looking for is an HTMLVideoElement, which inherits from HTMLMediaElement, which has a controls attribute.

Typescript is entirely correct: you told it you're working with an Element, and Typescript warns you that an Element is not known to have controls.

like image 133
deceze Avatar answered Oct 23 '22 05:10

deceze