svgdotjs / svgdom

Straightforward DOM implementation to make SVG.js run headless on Node.js
MIT License
269 stars 53 forks source link

README example doesn't work on TypeScript due to typings #118

Closed jacek-jablonski closed 9 months ago

jacek-jablonski commented 9 months ago

With below example:

import { createSVGWindow } from 'svgdom'
import { SVG, registerWindow } from '@svgdotjs/svg.js'

// returns a window with a document and an svg root node
const window = createSVGWindow()
const document = window.document

// register window and document
registerWindow(window, document)

// create canvas
const canvas = SVG(document.documentElement)

// use svg.js as normal
canvas.rect(100, 100).fill('yellow').move(50,50)

// get your svg as string
console.log(canvas.svg())
// or
console.log(canvas.node.outerHTML)

TS error occurs: Property 'rect' does not exist on type 'Dom'.ts(2339).

Should the typings be fixed or am I missing something?

Fuzzyma commented 9 months ago

Unfortunately SVG does not know what you pass in and will always return a Dom-Type which is the best guess it can do. That is the same problem as document.querySelector('.someClass') has. It will not give you back the specific HTML element type but just a generic HTMLElement.

The correct approach here is to type cast canvas to the appropriate type because in this circumstances you know more than typescript and thats what casting is for

jacek-jablonski commented 9 months ago

Thanks for explanation!