Typescript "Property does not exists on type Element"
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
.
lomboboo
Updated on September 10, 2020Comments
-
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 belowthis.video.controls
throws me a Typescript error Property 'controls' does not exists on type 'Element'.Temporary I changed
Element
type toany
, 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 about 7 yearsthanks, 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 about 7 yearsNo 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 ofElement
. -
Aluan Haddad over 3 yearsThis 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')
returnsHTMLElement | null
. You don't need an annotation or anas HTMLElement
assertion.document.getElementById('id_of_element')?.innerHTML = value
ordocument.getElementById('id_of_element')!.innerHTML = value;
depending on whether you want your app to crash if there element with that id.