I'm converting some Javascript code into Typescript. This is a cool Javascript function which uses d3 and wraps an svg text block perfectly. Normally I would just change the word "function" to "private" and the function will work as is in Typescript, but this one plains only about the getComputedTextLength() function. Would be great if someone can explain how I can make this function work in Typescript for myself and others, including why I'm getting the error. Visual Studio provides no help. Thanks.
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);
}
}
});
}
I'm converting some Javascript code into Typescript. This is a cool Javascript function which uses d3 and wraps an svg text block perfectly. Normally I would just change the word "function" to "private" and the function will work as is in Typescript, but this one plains only about the getComputedTextLength() function. Would be great if someone can explain how I can make this function work in Typescript for myself and others, including why I'm getting the error. Visual Studio provides no help. Thanks.
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);
}
}
});
}
One way could be to use assertion (i.e. we say to Typescript piler - I know what is returned type here). So this could be solution
Instead of this:
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
We could use this (e.g. here expecting that node should be 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) {
The 'SVGTSpanElement'
is ing from a mon lib.d.ts