Open In App

How to Perform String Interpolation in TypeScript?

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:



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




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.




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.




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

Article Tags :