为什么在$ in in typescript中使用返回tick

时间:2017-07-03 13:17:51

标签: angular typescript

我正在经历角度的turorial,我看到了下面的

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

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

有人可以解释为什么我需要在$ {之前使用`?由于这是打字稿和javascript类似,我不能使用

 this.heroesUrl + "/" + hero.id 

为什么我需要使用返回tick和$ {操作?

2 个答案:

答案 0 :(得分:12)

这称为Template literals,它是一个javascript功能,它不是特定于打字稿的。

是的,你确实可以取代它:

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

使用:

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

但是使用模板文字有时会更舒服,特别是当字符串由很多部分组成时。即:

const url1 = protocol + "://" + host + ":" + port + "/" + path + "." + extension;
const url2 = `${protocol}://${host}:${port}/${path}.${extension}`;

答案 1 :(得分:0)

认为它只是ES6 template literal的一部分,因此TypeScript继承/允许这一点(你不会被强制偶然使用它们),因为虽然TypeScript是ES5的超集,但它包含一些ES6功能。