Björn Hjorth Björn Hjorth - 1 year ago 207
Javascript Question

Typescript: Property 'src' does not exist on type 'HTMLElement'

I get a error from Typescript and I am not sure how to correct it. The code works fine when "compiled" but I can't correct the error. I have extracted the parts that involve the error from my code. I guess I have to predifine the src but not sure how.

Error msg in Editor and on Gulp compile:

"Property 'src' does not exist on type 'HTMLElement'.at line 53 col 17"


element:HTMLElement; /* Defining element */

this.element = document.createElement('img'); /*creating a img*/


This is the method I run to render the element, position, top and left all works with out giving a error.

display() {
this.element.src = this.file; /*This is the line that gives the error*/ = "absolute"; = this.pointX.toString() + "px"; = this.pointY.toString() + "px";


Answer Source

Because src is not a property of the HTMLElement type, but of HTMLImageElement.

If you are certain you'll get an img element, you might want to declare your variable with the correct subtype:

element: HTMLImageElement; /* Defining element */

// ...

this.element = document.createElement('img'); /*creating a img*/

Also, you might want to have a look at what document.createElement returns. It's the very same type if you specify "img" as its argument.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download