How to perform string interpolation in TypeScript?
How to perform string interpolation in TypeScript?
To perform string interpolation in TypeScript, you use template literals, which are string literals allowing embedded expressions. These template literals are enclosed by the backtick (`) character instead of the traditional single (' ') or double (" ") quotes. Within these literals, you can insert placeholders for variables or expressions using the syntax ${expression}.
Here's a basic example to illustrate string interpolation in TypeScript:
let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: Hello, John!
In the example above, the variable name
is interpolated into the string literal using the ${name} syntax within the backticks. This results in a dynamic string that includes the value of the name
variable.
String interpolation in TypeScript is not limited to variables; you can also embed expressions directly within the string. This allows for more complex constructions and operations to be performed right within the string literal:
let x = 5;
let y = 10;
let result = `The sum of ${x} and ${y} is ${x + y}.`;
console.log(result); // Outputs: The sum of 5 and 10 is 15.
In this second example, an addition operation is carried out within the interpolated string, showcasing the ability to perform calculations directly within the template literal.
It's important to use template literals consistently across y...
entry
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào