将JavaScript函数转换为TypeScript,包括getComputedTextLength()函数

10

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

错误描述是什么? - Buzinas
属性“getComputedTextLength”在类型“Element”上不存在。 - blissweb
这段代码来自Mike Bostock https://bl.ocks.org/mbostock/7555321 - 0x4a6f4672
1个回答

16

一种方法是使用断言(即我们告诉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 = <SVGTSpanElement>tspan.node(); - kolobok

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接