It is possible to interpolate Typescript where the variable is a string?

I need to interpolate a variable which is a string, but this no working. Is there any way to interpolate this variable? Is it better to do the substitution directly?

for example:

time = duration.years();
dateTime = this.i18nService.getTranslation('past-date-years');
//dateTime value is = "${time} years ago"

console.log(`${dateTime}`); //not working

console.log(`${time} years ago`);//working

Upvotes: 0

Views: 10599

Answers (2)

David J
David J

Reputation: 300

It's nasty, but it works:

const str = "Hello ${word}"
const word = "world"
const result = eval("`" + str + "`")
console.log(result)

Upvotes: 1

user8086575
user8086575

Reputation:

Since your string interpolation syntax is correct, this would mean that either dateTime is null or an empty string. Please add the output of your logged strings to your question and/or any errors that are showing up in the console.

Based on your comments below, it seems that you have a string interpolation within a string interpolation where the first hasn't been evaluated.

The following (rudimentary) code works:

let time = "This is time";
let vari = `${time} | is what we got`;
let result = `${vari} | is this possible?`;
document.body.innerText = result;

...which will print the result with all the variables resolved, but that's because TypeScript knows how to break those lines apart and construct a normal concatenation from them.

It seems that in your instance, getTranslation() isn't resolving time, but is instead constructing an escaped string with the interpolation tokens in it. That needs to be resolved appropriately.

Since TypeScript compiles to different targets, and string interpolation is essentially TypeScript doing string concatenations behind the scenes, you're going to have to do some legwork to write the code and evaluate the resulting JavaScript to see if it gives valid output that will resolve the variables appropriately.

Head over to the TypeScript play, and use that to check the output. You'll have to plug in some of what the getTranslation() method is doing, and see if the output will generate appropriately.

Upvotes: 2

Related Questions