user629283 user629283 - 1 year ago 158
TypeScript Question

naturalWidth - Property 'naturalWidth' does not exist on type 'HTMLElement'

I am trying to access "naturalWidth" in typescript however if I get a compile error or or i get a red line under "naturalWidth". Because $("#contentImg").height()) returns 0 for me in JavaScript and TypeScript I cant manipulate the image. The image varies in size. If I do it in javascript its fine. I have tried;


This works in JavaScript but not in TypeScript. Is there a way to get the naturalWidth/Height?

Answer Source

The document.getElementById returns an HTMLElement which lacks the naturalWidth property.
What you're looking for is the HTMLImageElement which does have this naturalWidth property:

let image =  document.getElementById('contentImg') as HTMLImageElement;
console.log(image.naturalWidth); // should be valid
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download