Skip to content

Instantly share code, notes, and snippets.

@kamauwashington
Last active September 4, 2022 23:33
Show Gist options
  • Save kamauwashington/9bb428040eaac213dbacd83093a8fae6 to your computer and use it in GitHub Desktop.
Save kamauwashington/9bb428040eaac213dbacd83093a8fae6 to your computer and use it in GitHub Desktop.

TypeScript Bits

Template Literals

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!

Before

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

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment