Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use back tick with ${ in const in typescript

I am going through the angular turorial and I see the below

https://angular.io/tutorial/toh-pt6

const url = `${this.heroesUrl}/${hero.id}`;

Can someone explain why I need to use ` before ${ ? Since this is typescript and similar to javascript can I not use

 this.heroesUrl + "/" + hero.id 

Why do I need to use back tick and the ${ operation?

like image 422
serah Avatar asked Jul 03 '17 13:07

serah


1 Answers

That is called Template literals and it's a javascript feature, it is not typescript specific.

True, you can indeed replace this:

const url = `${this.heroesUrl}/${hero.id}`;

With:

const url = this.heroesUrl + "/" + hero.id;

But it is sometimes more comfortable to use the template literals, especially when the string is made out of a lot of parts. i.e.:

const url1 = protocol + "://" + host + ":" + port + "/" + path + "." + extension;
const url2 = `${protocol}://${host}:${port}/${path}.${extension}`;
like image 155
Nitzan Tomer Avatar answered Oct 24 '22 02:10

Nitzan Tomer