TypeScript supports template literals, a JavaScript feature introduced in ES6 (ECMAScript 2015). Template literals are string literals that allow embedding expressions and are defined using backticks ( ).
Template literals not only support string interpolation but also preserve line breaks and formatting within the string. This is particularly useful when creating multi-line strings or inserting variables into strings.
Example
Suppose you are developing a web application and wish to display a dynamically generated welcome message. You can achieve this using template literals:
typescriptfunction getWelcomeMessage(user: string, time: Date): string { const hours = time.getHours(); let timeOfDay: string; if (hours < 12) { timeOfDay = "Good morning"; } else if (hours < 18) { timeOfDay = "Good afternoon"; } else { timeOfDay = "Good evening"; } return `Dear ${user}, ${timeOfDay}! Welcome back.`; } const user = "Zhang San"; const currentTime = new Date(); console.log(getWelcomeMessage(user, currentTime));
In this example, the function getWelcomeMessage accepts the username and current time, returning the appropriate greeting based on the time. This approach, using template literals to construct strings containing variables, is intuitive and effective.