Open In App

How to Perform String Interpolation in TypeScript?

Last Updated : 11 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

String interpolation is a special kind of syntax used to evaluate the string literals that contain expressions in it. It evaluates the expressions and replaces the result with the original string. String interpolation can be used in cases where a string can be generated from a static string or variables.

Laws for using TypeScript String Interpolation

There are some laws or rules that are applied to string interpolation in TypeScript:

  • String interpolation is enclosed inside the backticks (“) that show the start and end of it.
  • It evaluates the expression and replaces the placeholders with the result of the string literal.
  • The intermediate variables can be used for evaluating complex expressions and then placed inside the interpolation as placeholders.
  • Template strings can be implemented using interpolation, which is used to create strings with variable and static parts.
  • Templating is another name for the string interpolation.
  • The expressions can be placed using the ${} syntax inside the original string.

Example 1: The below example will explain the string interpolation with only one variable inside the original string.

Javascript




const org_name: string = "GeeksforGeeks";
console.log(`This organization is ${org_name}`);


Output:

This organization is GeeksforGeeks.

Example 2: This example will illustrate the string interpolation with more than one variable.

Javascript




const org_name: string = "GeeksforGeeks";
const org_desc: string = "A Computer Science portal for all geeks."
console.log(`Organization name ${org_name},
Organization Description: ${org_desc}`);


Output:

Organization name GeeksforGeeks, Organization Description: A Computer Science portal for all geeks.

Example 3: The below example will explain the string interpolation which evaluates the expressions.

Javascript




const num1: number = 1;
const num2: number = 8;
const num3: number = 3;
console.log(`Sum of Numbers ${num1} +
${num2} + ${num3} is:
 ${num1 + num2 + num3}`);
console.log(`Product of Numbers ${num1} * ${num2}
 * ${num3} is: ${num1 * num2 * num3}`);


Output:

Sum of Numbers 1 + 8 + 3 is: 12
Product of Numbers 1 * 8 * 3 is: 24


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads