Reputation: 2127
I am going through the angular tutorial 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 backtick and the ${
operation?
Upvotes: 20
Views: 25813
Reputation: 164367
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}`;
Upvotes: 37
Reputation: 5977
Think it's just a part of the ES6 template literal, and so TypeScript inherits/permits this (you're not forced to use them incidentally) because although TypeScript is a superset of ES5, it contains some ES6 features.
Upvotes: 1