类型 SVGElement 上不存在属性 getBBox

clb*_*clb 6 javascript svg types d3.js typescript

我正在使用 d3,我想使用 SVG 元素具有的 getBBox 方法。

我正在使用以下内容:(d3Selection.node() as SVGElement).getBBox(),但是由于标题中的错误,TypeScript 无法编译。

SVGElement 是错误的类型吗?我可以any改用它,但这似乎有点“不干净”的解决方案。

Rob*_*son 9

并非所有 SVG 元素都有边界框,<defs>例如没有,也没有<title>,所以是的 SVGElement 是错误的类型。你想要SVGGraphicsElement


千木郷*_*千木郷 9

而不是SVGElementSVGSVGElement是用于访问元素的正确类型<svg>,其中getBBox()方法也可用,因为继承自SVGGraphicsElement

(d3Selection.node() as SVGSVGElement).getBBox()
Run Code Online (Sandbox Code Playgroud)

或者如果d3Selection定义为

let d3Selection: D3.Selection<SVGSVGElement, {}, HTMLElement, any>
d3Selection.node().getBBox()
Run Code Online (Sandbox Code Playgroud)

可以直接投入使用。