Borislav Hadzhiev
Sat Mar 19 2022·2 min read
Photo by Chris Lawton
The error "Property 'play' does not exist on type 'HTMLElement'" occurs when
we try to call the play()
method on an element that has a type of
HTMLElement
. To solve the error, use a type assertion to type the element as
HTMLVideoElement
before calling play
.
This is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <video id="video" controls width="250"> <source src="/media/cc0-videos/flower.webm" type="video/webm" /> <source src="/media/cc0-videos/flower.mp4" type="video/mp4" /> Sorry, your browser doesn't support embedded videos. </video> <script src="./src/index.ts"></script> </body> </html>
And here is an example of how the error occurs in the index.ts
file.
// 👇️ const video: HTMLElement | null const video = document.getElementById('video'); if (video != null) { // ⛔️ Property 'play' does not exist on type 'HTMLElement'.ts(2339) video.play(); }
The reason we got the error is because the return type of the
document.getElementById
method is HTMLElement | null
and the
play
method doesn't exist on the HTMLElement
type.
To solve the error, use a type assertion to type the element as an
HTMLVideoElement
.
const video = document.getElementById('video') as HTMLVideoElement | null; if (video != null) { video.play(); }
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
video
variable stores anHTMLVideoElement
or a null
value and not to worry about it.We used a
union type
to specify that the variable could still be null
, because if an HTML element
with the provided id
does not exist in the DOM, the getElementById()
method
returns a null
value.
We used a simple if
statement that serves as a
type guard
to make sure the video
variable doesn't store a null
value before calling
its play()
method.
const video = document.getElementById('video') as HTMLVideoElement | null; // 👉️ video has type HTMLVideoElement or null here if (video != null) { // 👉️ video has type HTMLVideoElement here video.play(); }
video
variable has a type of HTMLVideoElement
in the if
block and allows us to directly call its play()
method.It's always a best practice to include null
in the type assertion, because the
getElementById
method would return null
if no element with the provided id
was found.
You might also use the
optional chaining (?.)
operator to short-circuit if the reference is equal to null
or undefined
const video = document.getElementById('video') as HTMLVideoElement | null; // 👇️ using optional chaining video?.play();
The optional chaining operator short-circuits returning undefined
if the
reference is equal to null
or undefined
.
In other words, if the video
variable stores a null
value, we won't attempt
to call the play()
method on null
and get a runtime error.