TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner, to intermediate to ninja, these bits are for you 😄
Estimated reading time : 2 minutes
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!
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!"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!"- 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!