EN
TypeScript - string templates
0 points
In this article, we would like to show you string templates in TypeScript.
Quick solution:
xxxxxxxxxx
1
const username: string = 'Tom';
2
const template: string = `User: ${username} logged in.`;
3
4
console.log(template); // User: Tom logged in.
In this example, we present step by step how to create template literals (string templates) in TypeScript.
1. Syntax
To define template literals, we need to use back-ticks (``
).
xxxxxxxxxx
1
const template: string = `Hello World!`;
2. Expression placeholders
Template literals can contain placeholders indicated by the dollar sign and curly braces (${expression}
).
xxxxxxxxxx
1
const x: number = 1;
2
const y: number = 2;
3
4
const template: string = `The result of x+y is ${x + y}.`;
5
6
console.log(template);
Output:
xxxxxxxxxx
1
The result of x+y is 3.