EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript string interpolation
Secondary Sidebar
TypeScript Tutorial
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type

TypeScript string interpolation

TypeScript string interpolation

Introduction to TypeScript String Interpolation

TypeScript String Interpolation is an expression used to evaluate string literals that contain one or more expressions. String Interpolation evaluates the expressions and obtains the result in a string, which is then replaced in the original string. In TypeScript, template strings are of 3 fold, i.e. String Interpolation, Multiline Strings, and Tagged Templates. String Interpolation had fallen backstep with other names as Dependency Injection, which apparently came up as Template literals in ES 6. 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, and that is how template strings come into the picture. Let us get into the syntax and its implementation.

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 of how this backtick is used.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Consider employeeName as the string expression. Evaluated beforehand and the resulting value “Karthik Kumar” is replaced as in the final string.

This particular string interpolation works only in ES6/ ES5 and above.

let employeeName:string = "Karthik Kumar";
console.log(`${employeeName} is one of the most valuable 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, code replaces the placeholders with real values

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,818 ratings)

How to Perform String Interpolation in TypeScript

Let us see few examples of How to Perform String Interpolation in TypeScript

Example #1

A basic example of TypeScript String Interpolation

let employeeName: string = "Karthik Kumar";
console.log(`${employeeName} is one of the most valuable Employee`)

Output:

TypeScript string interpolation output 1

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.

TypeScript String Interpolation 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 on to the resulting string.

Example #2

A basic example of TypeScript String Interpolation with Multiple Expressions

const empName: String = 'Lokesh';
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:

TypeScript string interpolation output 2

Here, ${ }, dollar with enclosed flower brackets will read the const values and is sent to the resulting string.

TypeScript String Interpolation using Expressions.

Interpolation of Expressions like Arithmetic expressions, Ternary operator can also be done using String Interpolation.

Example #3

String Interpolation for Arithmetic Expressions

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:

TypeScript string interpolation output 3

So here we are interpolating the Arithmetic expression of numA, numB and numC.

Example #4

String Interpolation using Ternary operator in the Template string.

let numX = 350;
console.log(`The numX value is ${(numX==350) ?'Three Hundred and Fifty':'Forty five'}`);

Output:

TypeScript string interpolation output 4

Here, we are using the Ternary operator to check the expression’s value and interpolate it in the console.

TypeScript String Interpolation for Nested Expressions,

As we had seen above in example 3, interpolation was applied to arithmetic expressions. Interpolation can also be applied to Nested expressions like `${a+b}`.

Example #5

String Interpolation for Nested Expressions

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:

output 5

So mulABC in the console log is nested with 3 other expressions numA, numB and numC.

Example #6

String Interpolation with string methods.

let stuName1 = 'Helen';
let stuName2 = 'Hari';
console.log(`Student ${stuName1.toUpperCase()} is taller than ${stuName2.toLowerCase()}`);

Output:

output 6

So here, string methods can also use string Interpolation.

Example #7

String Interpolation for functions

function squareArea(length: number, breadth: number): number {
return length * breadth;
}
console.log(`Area of the square is ${squareArea(2,4)}`);

Output:

output 7

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 denotes the string’s start and end.
  • Backticks are called Template literals and defined as String literals that have expressions embedded.
  • 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’s main usage is to use template strings that are created for building strings with static and variable parts.

Conclusion

With this, we shall conclude the topic ‘TypeScript String Interpolation’. We have seen what String Interpolation is and how is it 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 it helps in 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.

Recommended Articles

This is a guide to TypeScript string interpolation. Here we discuss How to Perform String Interpolation in TypeScript along with the examples and outputs. You may also have a look at the following articles to learn more –

  1. TypeScript Optional Parameters
  2. TypeScript Functions
  3. TypeScript Types
  4. What is TypeScript?
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more