乐闻世界logo
搜索文章和话题

Is String Interpolation Supported in TypeScript?

2024年8月7日 13:58

String interpolation can be used in TypeScript. String interpolation is also known as template literals, which allow embedding variables or expressions directly within strings. This makes string construction more convenient and intuitive.

In TypeScript, template literals are enclosed within backticks (), and variables or expressions are embedded within ${}`. This enables inserting relevant values or results into plain text seamlessly.

Here is a specific example:

typescript
function greet(name: string, age: number): string { return `Hello, my name is ${name} and I am ${age} years old.`; } const message = greet("Alice", 30); console.log(message); // Output: Hello, my name is Alice and I am 30 years old.

In this example, the greet function accepts two parameters, name and age, and returns a template literal utilizing these parameters. This approach is both clear and maintainable.

标签:TypeScript