2
votes

I am using d3 in my react application, where I write code using Typescript. I have the following code:

function mousemove() {
        // recover coordinate we need
        var x0 = xScale.invert(d3.mouse(this)[0]);
        var i = bisect(data, x0, 1);
        var selectedData = data[i]
        focus
            .attr("cx", xScale(selectedData.dateCreated))
            .attr("cy", yScale(selectedData[value]))
        focusText
            .html("x:" + selectedData.x + "  -  " + "y:" + selectedData.y)
            .attr("x", xScale(selectedData.dateCreated) + 15)
            .attr("y", yScale(selectedData[value]))
}

d3.mouse(this)[0] throws the following error:

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

Any suggestions to resolve it? This error is common typescript but I do not how to resolve it with d3.mouse function.

1

1 Answers

2
votes

I am assuming that this is a custom method passed to the d3.js's event handler (i.e .on('mousemove'))

Instead of referencing this, which might be inferred as an instance of your current class, you can handle the event callback by referencing the actual event handler.

.on('mousemove' (d, i) => {
  mousemove();
})

function mousemove() {
  const x0 = xScale.invert(d3.mouse(d3.event.currentTarget));
  // do the rest
}

Alternatively, you may pass the node to your mousemove() function. According to the documentation,

If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]).

.on('mousemove' (d, i, n) => {
  const node = d[i]
  mousemove(node);
})

function mousemove(node) {
      // do the rest
}