Convert Javascript function to Typescript, including getComputedTextLength ()

I am converting Javascript code to Typescript. This is a cool Javascript function that uses d3 and perfectly converts svg text block. Normally, I would simply change the word "function" to "private" and the function would work just like in Typescript, but this complaint only concerns the getComputedTextLength () function. It would be great if someone can explain how I can make this function work in Typescript for myself and others, including the reasons why I am getting an error. Visual Studio does not give any help. Thank you

function wrap(text, width) { text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 1.1, // ems y = text.attr("y"), x = text.attr("x"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan") .attr("x", x).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan") .attr("x", x).attr("y", y) .attr("dy", ++lineNumber * lineHeight + dy + "em") .text(word); } } }); } 
+6
source share
1 answer

One way could be to use a statement (i.e. we are talking to the Typescript compiler - I know that the type is returned here). So it could be a solution

Instead of this:

 while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { 

We could use this (e.g. expecting the node to be SVGTSpanElement )

 while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); var node: SVGTSpanElement = <SVGTSpanElement>tspan.node(); var hasGreaterWidth = node.getComputedTextLength() > width; if (hasGreaterWidth) { 

'SVGTSpanElement' comes from the generic lib.d.ts

+6
source

All Articles