Câu hỏi phỏng vấn Typescript
Câu hỏi

How to perform string interpolation in TypeScript?

Câu trả lời

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:

typescript Copy
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:

typescript Copy
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

entry

Gợi ý câu hỏi phỏng vấn

entry

What is TypeScript and why one should use it?

middle

Does TypeScript supports function overloading?

expert

Explain the difference between declare enum vs declare const enum

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào