Reputation: 309
I am working on to create a d3 line chart with react and typescript and referring to https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91 to achieve the mouse over functionality.
At one point we have to get the line element and check the total path length of line.
const linesElement: any = document.getElementsByClassName("line");
let beginning = 0,
end = linesElement[i].getTotalLength(),
target = null;
while (true){
target = Math.floor((beginning + end) / 2);
pos = linesElement[i].getPointAtLength(target);
if ((target === end || target === beginning) && pos.x !== mouse[0]) {
break;
}
if (pos.x > mouse[0]) end = target;
else if (pos.x < mouse[0]) beginning = target;
else break; //position found
}
When I declare type as any
I am getting Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type.tslint(no-any).
When I declare type as HTMLCollectionOf<Element>
I am getting the below error.
TS2339: Property 'getTotalLength' does not exist on type 'Element'.
TS2339: Property 'getPointAtLength' does not exist on type 'Element'
We do have a type restriction of using "any". So would like to know what is the better way to define lines
Upvotes: 1
Views: 2037
Reputation: 19214
getTotalLength
function is defined only on SVG and is absent on normal Element
interfaces. This is why this type error is happening.
What you can do here is to check if the element is an instance of SVGPathElement
:
if(linesElement[i] instanceof SVGPathElement) {
end = linesElement[i].getTotalLength();
}
Upvotes: 3