【问题标题】:Converting Javascript function to Typescript including getComputedTextLength()将 Javascript 函数转换为 Typescript,包括 getComputedTextLength()
【发布时间】:2015-12-24 14:55:54
【问题描述】:

我正在将一些 Javascript 代码转换为 Typescript。 这是一个很酷的 Javascript 函数,它使用 d3 并完美地包装了一个 svg 文本块。通常我只需将“函数”一词更改为“私有”,该函数将像在 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);
            }
        }
    });
}

【问题讨论】:

  • 错误描述是什么?
  • “元素”类型上不存在属性“getComputedTextLength”
  • 代码来自 Mike Bostock bl.ocks.org/mbostock/7555321

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


【解决方案1】:

一种方法是使用断言(即我们对 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

【讨论】:

  • 太好了,谢谢!此外,您可以将行缩短为 var node = &lt;SVGTSpanElement&gt;tspan.node();
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 2023-02-05
  • 2021-12-13
  • 2022-11-26
  • 2021-06-28
  • 2021-05-04
  • 2013-04-18
  • 1970-01-01
相关资源
最近更新 更多