jrierab jrierab - 10 months ago 106
TypeScript Question

Is there a valid typescript type for an SVG document embedded as an HTML object?

I am embedding an SVG object in HTML as follows:

<object id='mapObject' type="image/svg+xml" data="assets/maps/drawing.svg">

Then, I want to reach it from my typescript classes (from Ionic 2, but that should be indifferent):

let map = document.getElementById("mapObject");
let svgDoc = map.contentDocument; // Get the inner SVG DOM

This works on browser, but typescript complains about it:

typescript Property 'contentDocument' does not exist on type 'HTMLElement'

And worse, it doesn't work in the device, because the compiler refuses to generate code for it.

My temporary hack/solution is casting as follows:

let svgDoc = (<HTMLIFrameElement>map).contentDocument; // Get the inner SVG DOM

This works in the device, because HTMLIFrameElement has the contentDocument property, but it seems to me that typescript should have an specific type for this. However I've been unable to find it.


Answer Source

You can cast/assert it to HTMLObjectElement which has the contentDocument property:

let map = document.getElementById("mapObject") as HTMLObjectElement;
let svgDoc = map.contentDocument; // should be fine