Question
String Interpolation in TypeScript: Template Literals
Question
C# supports string interpolation with the $ prefix:
int value = 100;
Console.WriteLine($"The size is {value}.");
This prints:
The size is 100.
How can you insert variable values into a string in TypeScript to produce the same result?
Short Answer
TypeScript uses template literals for string interpolation. Write the string with backticks (`) and place a variable or expression inside ${...}. By the end, you will be able to create readable dynamic strings, include calculations, and avoid common quoting mistakes.
Concept
A template literal is a JavaScript and TypeScript string written with backticks instead of single or double quotes.
Inside a template literal, ${...} evaluates an expression and converts its result to text as part of the string.
const value: number = 100;
const message: string = `The size is ${value}.`;
console.log(message);
Output:
The size is 100.
This is TypeScript's equivalent of C# string interpolation. It matters because real programs constantly build messages from changing data: user names, error messages, URLs, log entries, labels, and API responses.
TypeScript type annotations such as : number are optional for this feature. Template literals work at runtime as standard JavaScript template literals.
Mental Model
Think of a template literal as a sentence with fillable slots.
- The backticks create the whole sentence.
- Each
${...}is a slot. - TypeScript evaluates what is inside the slot and inserts the result.
For example, in `Hello, ${name}!`, the text is the prewritten greeting and ${name} is the space where a person's name is placed.
Syntax and Examples
Use backticks, not regular quotation marks:
const name = "Ada";
const score = 42;
const message = `Player ${name} has ${score} points.`;
console.log(message);
Player Ada has 42 points.
${...} can contain more than a variable. It can contain any expression that produces a value:
const price = 19.99;
const quantity = 3;
console.log(`Total: $${price * quantity}`);
Total: $59.97
A template literal can also span multiple lines without manually adding \n:
const user = "Sam";
const report = `User: ${user}
Status: active`;
console.log(report);
User: Sam
Status: active
Step by Step Execution
Consider this code:
const width = 25;
const height = 4;
const areaMessage = `Area: ${width * height}`;
console.log(areaMessage);
Execution steps:
widthreceives the number25.heightreceives the number4.- TypeScript evaluates the expression inside
${width * height}. 25 * 4produces100.- The template literal becomes the string
Area: 100. console.logprints that string.
Output:
Area: 100
Real World Use Cases
Template literals are useful whenever text depends on values known while the program runs.
-
User-facing messages
const name = "Mina"; const message = `Welcome back, ${name}!`; -
Logging and debugging
console.log(`Request ${requestId} failed with status ${statusCode}`); -
Building URLs
const userId = 42; const url = `/api/users/${userId}`; -
Generating reports
const completed = 8; const total = 10; const report = `Completed ${completed} of ${total} tasks.`; -
Displaying formatted data
const amount = 1250.5; const label = `Balance: ${amount.toFixed(2)}`;
Real Codebase Usage
In production code, template literals are usually kept simple and combined with validation and formatting.
Use guard clauses before creating a message
function createGreeting(name: string | undefined): string {
if (!name) {
return "Hello, guest!";
}
return `Hello, ${name}!`;
}
Format values before interpolation
const createdAt = new Date();
const formattedDate = createdAt.toLocaleDateString("en-US");
const message = `Created on ${formattedDate}`;
Use template literals in error messages
function findProduct(productId: string): void {
throw new Error(`Product with ID ${productId} was not found.`);
}
Build paths from known values
function getOrderPath(orderId: string): string {
return `/orders/${orderId}`;
}
For complex display formatting, developers often calculate named intermediate values first. This keeps template strings readable instead of placing large expressions inside ${...}.
Common Mistakes
Using quotes instead of backticks
This does not interpolate the variable:
const value = 100;
console.log("The size is ${value}.");
Output:
The size is ${value}.
Use backticks:
console.log(`The size is ${value}.`);
Forgetting the dollar sign
${value} is interpolation syntax. {value} alone is ordinary text.
const value = 100;
console.log(`The size is {value}.`);
Correct:
console.log(`The size is ${value}.`);
Treating a template literal as an expression without ${}
const value = 100;
console.log(`The size is value.`);
The word value is literal text. Add ${value} to insert the variable's value.
Confusing string interpolation with type safety
Template literals convert values to text; they do not validate data. For example, an optional value may display as undefined:
const name: string | undefined = undefined;
console.log(`Hello, ${name}`);
Provide a fallback when needed:
console.log(`Hello, ${name ?? "guest"}`);
Putting overly complex logic in a template
This is valid but difficult to read:
const text = `Total: ${items.filter(item => item.active).reduce((sum, item) => sum + item.price, 0)}`;
Prefer calculating the value first, then interpolating it.
Comparisons
| Approach | Example | Best use |
|---|---|---|
| Template literal | `Hello, ${name}!` | Dynamic strings; readable messages and expressions |
| String concatenation | "Hello, " + name + "!" | Older code or very simple strings |
| Literal string | "Hello!" | Text that never changes |
| C# interpolation | $"Hello, {name}!" | The C# equivalent of TypeScript template literals |
Template literals are generally easier to read than concatenation, especially with multiple values:
const firstName = "Ada";
const lastName = "Lovelace";
const withConcatenation = "User: " + firstName + " " + lastName;
const withTemplateLiteral = `User: ${firstName} ${lastName}`;
Both produce the same result, but the template literal more closely resembles the final sentence.
Cheat Sheet
// Basic interpolation
const name = "Ada";
const message = `Hello, ${name}!`;
// Insert an expression
const count = 4;
const nextCount = `Next: ${count + 1}`;
// Call a method
const title = `Name: ${name.toUpperCase()}`;
// Fallback for null or undefined
const optionalName: string | undefined = undefined;
const greeting = `Hello, ${optionalName ?? "guest"}!`;
// Multi-line text
const text = `First line
Second line`;
Rules:
- Use backticks:
`...`. - Put values and expressions inside
${...}. - Single quotes (
'...') and double quotes ("...") do not interpolate. - Values are converted to strings automatically.
- Use
??to provide a fallback fornullorundefined.
FAQ
What is string interpolation in TypeScript?
It is the process of inserting values into a string. TypeScript does this with template literals, using backticks and ${...}.
Does TypeScript use $"..." like C#?
No. TypeScript uses backticks: `The size is ${value}.`. It does not use a $ before the opening quote.
Can I put calculations inside ${...}?
Yes. Any valid expression can be used.
const message = `Result: ${10 * 5}`;
Can I interpolate objects in a template literal?
You can, but a plain object usually becomes [object Object].
const user = { name: "Ada" };
console.log(`User: ${user.name}`);
For debugging a full object, use JSON.stringify(user) when appropriate.
Are template literals available in JavaScript too?
Yes. Template literals are a JavaScript feature, and TypeScript supports them with type checking.
Can template literals contain multiple lines?
Yes. New lines written between the backticks are preserved.
Should I use template literals instead of string concatenation?
Usually yes for dynamic text. They are generally clearer, particularly when a string contains multiple variables or expressions.
Mini Project
Description
Create a small order-summary formatter. It receives product information and produces a readable message that could be shown in a checkout page, confirmation email, or application log. The project demonstrates inserting variables, calculations, and formatted values into a TypeScript template literal.
Goal
Build a function that returns a formatted summary for an order using a template literal.
Requirements
- Create an
Orderinterface with product name, unit price, and quantity. - Write a function named
createOrderSummarythat accepts anOrder. - Calculate the total price from the unit price and quantity.
- Return a multi-line summary using a template literal.
- Format the total with exactly two decimal places.
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Accessing Input Value from EventTarget in TypeScript
Learn why EventTarget has no value property in TypeScript and safely read values from HTML input events in Angular applications.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.