← All posts TypeScript Bits
KAMAU WASHINGTON
TypeScript Bits 2 min read Novice September 5th, 2022

Template Literals


In many TS code-reviews one may find string concatenation (with the addition operator) used to assemble a message, query, multi-line comments, or other manners of literals. While this gets the job done, it is often prone to error, difficult to read, and in many cases tedious to refactor and or implement.

TypeScript (and ES6) added Template Literals, and the TS/JS world couldn’t be happier!

Before

typescript
const firstName : string = "Jane";
const lastName :  string = "Smith";
const message : string = "A person with the first name of " + firstName + " and the last name of " + lastName + " says hello!";
console.log(message) // A person with the first name of Jane and the last name of Smith says hello!"

After

typescript
const firstName : string = "Jane";
const lastName :  string = "Smith";
const message : string = `A person with the first name of ${firstName} and the last name of ${lastName} says hello!`;
console.log(message) // A person with the first name of Jane and the last name of Smith says hello!"

Notes

  • this “magic” happens when backticks are used to encapsulate a string vs ticks or quotes
  • you can use full expressions inside of the ${expresssion|variable-name} directive
  • use the backtick to create multi-line strings as well without using newline and the addition operator
  • TS Template Literals are POWERFUL much more than is shown above!

Visit the TypeScript Documentation for Template Literals for more in-depth information!

Tagged interpolationjavascriptnodejstemplatingtypescript