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

Converting Javascript function to Typescript including getComputedTextLength()

本文关键字:包括 getComputedTextLength Typescript Javascript 函数 转换      更新时间:2023-09-26

我正在将一些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);
            }
        }
    });
}

一种方法是使用断言(即我们对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'来自一个公共库。d。ts