Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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*/
   this.element.style.position = "absolute";
   this.element.style.top = this.pointX.toString() + "px";
   this.element.style.left = this.pointY.toString() + "px";

   document.body.appendChild(this.element);
};
like image 821
Björn Hjorth Avatar asked Feb 21 '16 21:02

Björn Hjorth


2 Answers

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.

like image 144
John Weisz Avatar answered Nov 11 '22 22:11

John Weisz


Using casting:

(<HTMLImageElement>document.querySelector(".company_logo")).src
like image 35
Oded Breiner Avatar answered Nov 11 '22 21:11

Oded Breiner