Skip to main content

TypeScript Multiline Strings

When working with strings in TypeScript, sometimes a single line just doesn't cut it. Whether you're building HTML templates, writing SQL queries, or constructing complex JSON objects, TypeScript's multiline strings make these tasks significantly easier. They let you spread text over several lines, making it easier to read and manage. This article will explore how to create and format multiline strings, include variables and expressions, handle special characters, and more.

Creating Multiline Strings with Template Literals

To make a multiline string in TypeScript, you use template literals, which are created by wrapping your string in backticks (`) instead of quotes. This lets you write your string over multiple lines without needing to join them or use special newline characters.

const multilineString = `
This is a multiline string.
It can span multiple lines.
`;

console.log(multilineString);

This will output the string exactly as written, preserving the line breaks. Unlike older JavaScript approaches that required concatenation with \n characters, template literals make multiline text straightforward and readable.

Improving Readability of Multiline Strings

Good formatting is important, especially with large text blocks or structured content like HTML or JSON. Keep proper indentation in your multiline strings to make them more readable.

const htmlString = `
<div>
<h1>Heading</h1>
<p>Paragraph of text.</p>
</div>
`;

console.log(htmlString);

The indentation in your template literal will be preserved in the output, making it easier to visualize the structure. This is particularly useful when working with string interpolation or when generating HTML templates for web applications.

You can also use this approach when working with Convex query functions that return formatted data:

const userTemplate = `
User: ${user.name}
Role: ${user.role}
Last Active: ${formatDate(user.lastActive)}
`;

Adding Variables within Multiline Strings

You can add variables to multiline strings using template literals by placing the variable name inside ${}.

const name = "John Doe";
const greeting = `
Hello, ${name}!
Welcome to our application.
`;

console.log(greeting);

This feature, known as string interpolation, allows you to insert any valid TypeScript expression inside the ${} placeholder. You can include variables, function calls, or even complex expressions:

const items = ["apple", "banana", "orange"];
const itemList = `
You have ${items.length} items in your cart:
${items.map((item, index) => `${index + 1}. ${item}`).join('\n')}
`;

When building applications with Convex, you can leverage this technique to format data retrieved from your database before sending it to your frontend.

Managing Special Characters in Multiline Strings

Special characters like quotes, backslashes, and newlines can mess up formatting if not handled properly. Use backslashes to escape these characters.

const specialCharsString = `
This string contains a "quote" and a \\ backslash.
It also spans multiple lines with a newline at the end of this line.
${"\n"}And this text is on a new line.
`;

console.log(specialCharsString);

For explicit control over line breaks, you can use the \n escape sequence within expressions:

const formattedText = `First line${"\n"}Second line after an explicit break`;
console.log(formattedText);

This explicit control becomes useful when working with template literals in complex string manipulation scenarios, especially when building complex filters in Convex where string formatting is critical.

Joining Multiple Strings into One Multiline String

You can join multiple strings into one multiline string with the + operator or by using template literals.

const firstPart = "This is the first part of the string.";
const secondPart = `
This is the second part,
spanning multiple lines.
`;

const fullString = firstPart + "\n" + secondPart;
console.log(fullString);

Alternatively, using template literals for cleaner joining:

const fullStringTemplate = `${firstPart}
${secondPart}`;

console.log(fullStringTemplate);

Method 2 is generally preferred as it maintains readability. This technique is particularly useful when building complex text outputs in TypeScript applications or when working with Convex backend functions that need to format data from multiple sources.

You can also join arrays of strings into a multiline string using the join() method:

const paragraphs = [
"First paragraph",
"Second paragraph",
"Third paragraph"
];

const document = paragraphs.join("\n\n");

console.log(document);

Using Expressions Inside Multiline Strings

Expressions can be included in multiline strings by wrapping them in ${}.

const count = 5;
const listString = `
You have ${count} items in your list.
${count > 1 ? "They are:" : "It is:"}
Item 1
${count > 1 ? `Item 2` : ``}
`;

console.log(listString);

This example shows how to use conditional expressions within template literals to change text based on values, and demonstrates generating list items dynamically. You can even nest template literals for more complex structures:

const user = { name: "Alice", role: "Admin", tasks: ["Review", "Approve"] };
const userSummary = `
User: ${user.name}
Role: ${user.role}
Tasks: ${user.tasks.length > 0 ?
`\n${user.tasks.map(task => ` - ${task}`).join('\n')}` :
"None assigned"}
`;

console.log(userSummary);

This approach is valuable when building reactive UIs with Convex where you need to format and display information from the database without managing multiple state variables.

Keeping Indentation and Spacing in Multiline Strings

To keep indentation and spacing, make sure each line of your multiline string is aligned properly, especially when dealing with nested structures.

const nestedString = `
Outer level
Inner level
Deeply nested level
`;

console.log(nestedString);

For programmatically generated text with consistent indentation, use functions to handle the formatting:

function indent(text: string, spaces: number): string {
const padding = ' '.repeat(spaces);
return text.split('\n').map(line => line ? padding + line : line).join('\n');
}

const baseText = `Header
Content
Footer`;

const formattedText = indent(baseText, 4);
console.log(formattedText);

This technique works well when generating code or structured documents in TypeScript projects. When working with Convex database queries, you can format query results with proper indentation before displaying them.

For large JSON structures or complex HTML, controlling indentation makes debugging and maintaining the code more manageable:

const jsonTemplate = `{
"user": {
"name": "${userName}",
"permissions": [
${permissions.map(p => `"${p}"`).join(',\n ')}
]
}
}`;

Final Thoughts on TypeScript Multiline Strings

Multiline strings in TypeScript simplify working with complex text. Whether you're:

  • Crafting HTML templates
  • Writing SQL queries
  • Building JSON structures
  • Generating formatted reports

Template literals make these tasks more readable and maintainable. The ability to embed expressions, preserve formatting, and avoid escape character headaches saves time and reduces errors.

With practice, you'll find that multiline strings become an essential tool in your TypeScript development workflow. They help you write cleaner code that's easier to understand and modify, especially when dealing with text-heavy applications.

For more TypeScript tips, check out our guides on string manipulation and end-to-end type safety with Convex.