2015-09-27 54 views
6

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

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

什么是错误描述? – Buzinas

+0

Property'getComputedTextLength'在类型'元素'上不存在 – blissweb

+0

该代码来自Mike Bostock https://bl.ocks.org/mbostock/7555321 – 0x4a6f4672

回答

6

的一种方法是使用断言(即我们说的打字稿编译器 - 我知道什么是返回类型这里)。因此,这可能是解决方案

取而代之的是:

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

+0

当然可以修复问题。 :-)你是超级巨星。非常感谢。 – blissweb

+0

很高兴看到! ;)享受打字稿,先生... –

+0

太好了,谢谢!另外,你可以将行缩短为'var node = tspan.node(); ' – kolobok