将typescript const变量与类变量一起使用的最佳实践?

时间:2016-09-01 04:25:12

标签: angular typescript

使用此代码(在angular2服务中),我可以看到它的工作原理,我猜这些反引号允许评估this.heroesUrl和hero.id就好像它在模板中一样:

    const url = `${this.heroesUrl}/${hero.id}`;
    return this.http
        .put(url, JSON.stringify(hero), {headers: this.headers})
        .toPromise()
        .then(() => hero)
        .catch(this.handleError);

问题是,我可以做到这一点:

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

如果是这样,那么前者仍然比第二种最佳实践更受欢迎吗?

1 个答案:

答案 0 :(得分:1)

该示例使用es2015模板文字。在这种情况下,它们都是等效的,但模板文字可用于计算字符串内的表达式。

例如,如果您想在字符串中添加两个变量:

  1. ES5:var sum = 'The sum is: ' + (a + b);
  2. ES2015:let sum =`总和为$ {a + b}`