Borislav Hadzhiev
Sun Mar 27 2022·2 min read
Photo by Dylan Calluy
The error "Property 'src' does not exist on type 'Element'" occurs when we try
to access the src
property on an element that has a type of Element
. To
solve the error, use a type assertion to type the element as HTMLImageElement
before accessing the property.
This is the index.html
file for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <img id="photo" width="400" height="400" src="dog.jpg" /> <script src="./src/index.ts"></script> </body> </html>
And here is an example of how the error occurs in the index.ts
file.
// 👇️ const image: Element | null const image = document.querySelector('#photo'); if (image != null) { // ⛔️ Property 'src' does not exist on type 'Element'.ts(2339) image.src = 'photo.jpg'; }
The reason we got the error is because the return type of the
document.querySelector
method is Element | null
and the
src
property doesn't exist on the Element
type.
To solve the error, use a type assertion to type the element as an
HTMLImageElement
.
const image = document.querySelector('#photo') as HTMLImageElement | null; if (image != null) { image.src = 'photo.jpg'; }
If you used the
document.getElementsByClassName
method, type the collection as HTMLCollectionOf<HTMLImageElement>
.
// 👇️ with getElementsByClassName // type as HTMLCollectionOf<HTMLImageElement> const images = document.getElementsByClassName( 'img', ) as HTMLCollectionOf<HTMLImageElement>; for (let i = 0; i < images.length; i++) { images[i].src = 'photo.jpg'; }
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
image
variable stores anHTMLImageElement
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 selector does not exist in the DOM, the querySelector()
method returns a null
value.
We used a simple if
statement that serves as a
type guard
to make sure the image
variable doesn't store a null
value before accessing
its src
property.
const image = document.querySelector('#photo') as HTMLImageElement | null; // 👉️ image has type HTMLImageElement or null here if (image != null) { // 👉️ image has type HTMLImageElement here image.src = 'photo.jpg'; }
image
variable has a type of HTMLImageElement
in the if
block and allows us to directly access its src
property.It's always a best practice to include null
in the type assertion, because the
querySelector
method would return null
if no element with the provided
selector was found.