Explain Codes LogoExplain Codes Logo

How to perform string interpolation in TypeScript?

javascript
template-literals
string-interpolation
typescript
Nikita BarsukovbyNikita Barsukov·Feb 19, 2025
TLDR

For interpolating strings in TypeScript, you'll want to use template literals enclosed in backticks (`) and ${} placeholders:

const user = 'Bob'; const message = `Hi, ${user}!`; // Outputs: "Hi, Bob!"

Dive into the details

Crafting multi-line strings

An essential feature of template literals is the ability to create multi-line strings without + operator:

const item = 'java bean juice'; const quantity = 3; console.log(`You've ordered: - ${quantity} cups of ${item}`);

Output:

You've ordered: - 3 cups of java bean juice

It's like your code is writing a tiny essay, adorable isn't it?

Execute expressions directly

Expressions can be evaluated directly through placeholders:

const singlePrice = 2.5; const orderQuantity = 3; console.log(`Total due: $${(singlePrice * orderQuantity).toFixed(2)}`); // "Total due: $7.50"

Math homework in your strings, who would've thought?

Nested template literals

Nesting template literals allows dynamic composition of strings:

const adjective = 'epic'; const noun = 'saga'; console.log(`This is ${ `an ${adjective} ${noun}` } project.`); // "This is an epic saga project."

Enhancing your code

Readability and maintenance

Template literals can significantly boost readability and maintenance of your code by:

  • Minimizing concatenation errors.
  • Creating a visual blueprint of the final string.
  • Supporting refactoring of variable names without order and concatenation worries.

C# analogies and TypeScript

If you're a C# programmer, the syntax of TypeScript's template literals will remind you of C#'s string interpolation functionality, paving a smoother path to TypeScript.

// In C# string name = "world"; string greeting = $"Hello, {name}!";
// In TypeScript const name = 'world'; const message = `Hello, ${name}!`;

They both like to play around with {} and string. Not so foreign after all, isn't it?

Watch out for pitfalls

  • Ensure you're using backtick (`), not the quote marks for interpolation.
  • Remember to escape the backtick characters in strings.
  • Complex expressions should be avoided inside placeholders for readability.

Advanced magic tricks

TypeScript's advanced type system empowers your string interpolation to perform more advanced tricks:

  • Define types that mirror dynamic string values.
  • Use utility types to compose types based on strings.
  • Directly validate string patterns in type declarations.