Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Javascript function to Typescript including getComputedTextLength()

I'm converting some Javascript code into Typescript. This is a cool Javascript function which uses d3 and wraps an svg text block perfectly. Normally I would just change the word "function" to "private" and the function will work as is in Typescript, but this one complains only about the getComputedTextLength() function. Would be great if someone can explain how I can make this function work in Typescript for myself and others, including why I'm getting the error. Visual Studio provides no help. Thanks.

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);
            }
        }
    });
}
like image 987
blissweb Avatar asked Sep 27 '15 05:09

blissweb


1 Answers

One way could be to use assertion (i.e. we say to Typescript compiler - I know what is returned type here). So this could be 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. here expecting that node should 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) {

The 'SVGTSpanElement' is coming from a common lib.d.ts

like image 75
Radim Köhler Avatar answered Sep 30 '22 10:09

Radim Köhler