首页 > 解决方案 > D3.js:“this”隐含类型“any”,因为它没有类型注释

问题描述

我使用 3D.js 库:

d3.select(`#myGraph`)
  .append('svg')

const svg = d3.select(`#myGraph svg`).append('g')

const nodeEnter = svg.selectAll("g.node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("class", "node")
  .call(force.drag())

svg.selectAll(".node")
      .each(function (d: any) {
        d3.select(this)
          .attr("data-source", d.id)
      })

但我得到了错误:'this' 隐含类型'any',因为它没有类型注释

没有 @ts-ignore 怎么解决?

标签: typescriptd3.js

解决方案


您可以将类型注释添加到this函数中:

  svg.selectAll(".node")
      .each(function (this: any, d: any) {
        d3.select(this)
          .attr("data-source", d.id)
      })

或者,如果您不想要明确的any,您可以将其定义为SVGGraphicsElement,这是一种通用的 SVG 元素类型。如果您想更详细,可以使用更具体的类型(例如SVGRectElementSVGGElement)来更好地描述选择。

  svg.selectAll(".node")
      .each(function (this: SVGGraphicsElement, d: any) {
        d3.select(this)
          .attr("data-source", d.id)
      })

推荐阅读