Updated September 8, 2023
Introduction to TypeScript String Interpolation
String interpolation in TypeScript evaluates expressions within string literals, producing a resulting string that replaces the original one. This process involves actively evaluating expressions and substituting them in the original string. In TypeScript, template strings are threefold, i.e., String Interpolation, Multiline Strings, and Tagged Templates. String Interpolation had fallen backstep with other names, such as Dependency Injection, which came up as Template literals in ES6. A common use of String Interpolation is when the user wants to generate some string out of static string and variables, which require templating logic; that is how template strings come into the picture. Let us get into the syntax and its implementation.
Table of Contents
Syntax
There is no particular syntax for String Interpolation, but we need to use strings that use backticks, i.e. ` instead of single quote ‘or double quotes “enclosed with placeholders as ${ }
Let us see an example to use backtick.
Consider employeeName as the string expression. The resulting value “John Desouza” is evaluated beforehand and replaced as in the final string.
This particular string interpolation works only in ES6/ ES5 and above.
let employeeName:string = "Calvin";
console.log(`${employeeName} is Best Employee`)
Here, we are using the backticks for the output log to print. Previously, we used to put them in single quotes or double quotes.
At runtime, the code replaces the placeholders with real values.
How to Perform String Interpolation in TypeScript?
Let us see a few examples of Perform String Interpolation in TypeScript:
Example #1
A basic example of TypeScript String Interpolation.
Code:
let employeeName:string = "John Desouza";
console.log(`${employeeName} is one of the most valuable Employee`)
Output:
Here, we are using a single expression in the resulting string. $ { }, dollar with enclosed flower brackets will read the variable and is sent to the resulting string.
Example #2 – With Multiple Expressions
Interpolation of more than one expression at a time leads to Multiple Interpolations. In the below example, we shall pass three expressions for Interpolation and then display them onto the resulting string.
A basic example of TypeScript String Interpolation with Multiple Expressions
Code:
const empName: String = 'Daniel';
const empExp: number = 15;
const empPrd: String = 'RCL';
let empVal: string = `Employee ${ empName } has experience of ${ empExp } years in domain ${ empPrd }`;
console.log('Valuable Employee:',empVal);
Output:
Here, ${ }, dollar with enclosed flower brackets will read the const values and is sent to the resulting string.
Example #3 – Using Expressions
Expressions like Arithmetic expressions and Ternary operators can also be interpreted using String Interpolation.
String Interpolation for Arithmetic Expressions
Code:
let numA=102
let numB=202
let numC=302
let addABC=`${numA+numB+numC}`
console.log(`The addition of ${numA} + ${numB} + ${numC} is ${addABC}`);
Output:
So here we are interpolating the Arithmetic expression of numA, numB, and numC.
Example #4 – Using the Ternary operator in the Template string
Code:
let numX = 350;
console.log(`The numX value is ${(numX==350) ?'Three Hundred and Fifty':'Forty five'}`);
Output:
Here, the Ternary operator checks and interpolates the expression’s value in the console.
Example #5 – For Nested Expressions
As seen in example 3, interpolation was applied to arithmetic expressions. Interpolation can also be applied to Nested expressions like `${a+b}`.
String Interpolation for Nested Expressions
Code:
let numA=2
let numB=4
let numC=6
let mulABC=`${numA*numB*numC}`
console.log(`The Multiplication of ${numA} * ${numB} * ${numC} is ${mulABC}`);
Output:
So mulABC in the console log is nest three with three other exp:ressions numA, numB, and numC.
Example #6 – With string methods
Code:
let stuName1 = 'Helen';
let stuName2 = 'Henry';
console.log(`Student ${stuName1.toUpperCase()} is taller than ${stuName2.toLowerCase()}`);
Output:
So here, string methods can also use string Interpolation.
Example #7 – For functions
Code:
function squareArea(length: number, breadth: number): number {
return length * breadth;
}
console.log(`Area of the square is ${squareArea(2,4)}`);
Output:
Interpolation can also be applied to functions, as shown above.
Rules and Regulations for TypeScript String Interpolation
- String Interpolation replaces the placeholders with values of string literals of any type.
- As these are very useful in the modern programming language, in TypeScript, they are enclosed using backticks “which denote the string’s start and end.
- Backticks define Template literals, which are strings containing embedded expressions.
- String interpolation is also known as templating.
- It is better to use intermediate variables to hold the complex expressions before sending them to the placeholder.
- Interpolation primarily involves using template strings to construct strings with both static and variable components.
Conclusion
With this, we shall conclude the topic ‘TypeScript String Interpolation’. We have seen what String Interpolation is. It is displayed using the backticks enclosed in flower brackets. The template string wraps a sequence of characters into a pair of backticks. Interpolation has a future as inserting the values to string literals in a readable format. If, in case, template strings use complex expressions, it is better to have intermediate variables to hold the expressions before sending them to the placeholders. Examples solved here have covered all the concepts using string interpolation.
FAQs
Q1. Is string interpolation type-safe in TypeScript?
Answer: Yes, TypeScript provides type safety when using string interpolation with template literals. Preserving the type of the interpolated expression ensures that you avoid accidentally concatenating incompatible types.
Q2. Are there any limitations to string interpolation in TypeScript?
Answer: String interpolation is powerful, but you should exercise caution when directly incorporating user input into a string, as it can potentially result in security vulnerabilities such as SQL injection or cross-site scripting (XSS). Always sanitize or escape user-generated content before interpolating it into a string.
Q3. Is string interpolation in TypeScript more efficient than string concatenation?
Answer: String interpolation using template literals can often be more efficient than traditional string concatenation, especially when dealing with complex expressions and large strings. It can lead to cleaner and more readable code.
Recommended Articles
We hope that this EDUCBA information on “TypeScript string interpolation” was beneficial to you. You can view EDUCBA’s recommended articles for more information.