将Javascript函数转换为Typescript,包括getComputedTextLength()

时间:2015-09-27 05:12:34

标签: javascript visual-studio d3.js svg typescript

我正在将一些Javascript代码转换为Typescript。 这是一个很酷的Javascript函数,它使用d3并完美地包装svg文本块。通常我只是将“function”改为“private”,函数将在Typescript中工作,但是这个只会抱怨getComputedTextLength()函数。如果有人可以解释我如何使这个功能在我自己和他人的Typescript中工作,包括为什么我收到错误,那将会很棒。 Visual Studio没有提供任何帮助。谢谢。

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

1 个答案:

答案 0 :(得分:9)

一种方法可能是使用断言(即我们对Typescript编译器说 - 我知道这里返回的是什么类型)。所以这可能是解决方案

而不是:

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

我们可以使用此(例如,此处期望该节点应为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'来自常见的lib.d.ts