Typescript "Property does not exists on type Element"

25,109

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.

Share:
25,109
lomboboo
Author by

lomboboo

Updated on September 10, 2020

Comments

  • lomboboo
    lomboboo over 3 years

    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

  • lomboboo
    lomboboo about 7 years
    thanks, I've got it work like this: private video: HTMLVideoElement = <HTMLVideoElement>this.container.getElementsByClassName( 'video' )[ 0 ];. But one thing I don't understand why I need to cast <HTMLVideoElement>? Typescript can't figure that this is video type?
  • Gromski
    Gromski about 7 years
    No it cannot. What element exactly will be returned by getElementsByClassName('video') is only known at runtime, not at compile time. At compile time the best Typescript can infer is that it's going to be some sort of Element.
  • Aluan Haddad
    Aluan Haddad over 3 years
    This has nothing to do with the question and it is very poor code. You have a misleading annotation and completely redundant annotation that is only allowed by TS because of an unsafe type assertion. document.getElementById('id_of_element') returns HTMLElement | null. You don't need an annotation or an as HTMLElement assertion. document.getElementById('id_of_element')?.innerHTML = value or document.getElementById('id_of_element')!.innerHTML = value; depending on whether you want your app to crash if there element with that id.