Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js: 'this' implicitly has type 'any' because it does not have a type annotation

I use 3D.js library:

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)
      })

But I got the error: 'this' implicitly has type 'any' because it does not have a type annotation

How can I fix it without @ts-ignore ?

like image 200
Kirill Avatar asked Aug 31 '25 10:08

Kirill


1 Answers

You can add the type annotation to the this in the function:

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

Or, if you don't want the explicit any, you can define it as SVGGraphicsElement, which is a general SVG element type. If you want to be more detailed it can be a more specific type (such as SVGRectElement or SVGGElement) to better describe the selection.

  svg.selectAll(".node")
      .each(function (this: SVGGraphicsElement, d: any) {
        d3.select(this)
          .attr("data-source", d.id)
      })
like image 180
Rodrigo Divino Avatar answered Sep 03 '25 01:09

Rodrigo Divino