Working with Multiline Strings in TypeScript

Working with multiline strings is a common occurrence in my TypeScript projects. Whether I’m creating HTML templates, SQL queries, or formatted text outputs, handling text that spans multiple lines is essential.

In the past, concatenating strings with the + operator or using arrays with join() were common workarounds. But TypeScript, following JavaScript’s evolution, now offers elegant solutions for multiline strings.

In this article, I’ll show you multiple ways to create and work with multiline strings in TypeScript, from the modern template literals to alternative approaches for specific use cases. So let’s dive in!

I will recommend practicing with these examples to learn more.

Here are a few useful methods to create multiline strings in TypeScript with examples.

Using Template Literals (Backticks)

The most common and recommended way to create multiline strings in TypeScript is using template literals with backticks (`).

Here is an example.

let multilineString = `This is a string
that spans across
multiple lines.`;

console.log(multilineString);

When you run this code, the output preserves the line breaks exactly as written in the source:

This is a string
that spans across
multiple lines.

I executed the above TypeScript code using VS Code, and you can see the exact output in the screenshot below:

typescript multiline string

Template literals were introduced in ES6 (ECMAScript 2015) and are fully supported in TypeScript. They’re my go-to solution for multiline strings because they’re clean, intuitive, and preserve formatting.

Check out Compare Strings in TypeScript

Benefits of Template Literals

Here are some benefits of using template literals for creating multiline strings in TypeScript.

  1. Readability: The code structure visually represents how the string will appear
  2. No escape characters needed: You don’t need to use \n for line breaks
  3. String interpolation: You can embed expressions using ${expression} syntax

Here’s an example using string interpolation:

const userName = "John";
const items = ["Coffee", "Bagel", "Orange Juice"];

const receipt = `Hello ${userName},

Your order contains:
${items.map(item => `- ${item}`).join('\n')}

Thank you for your purchase!`;

console.log(receipt);

This produces:

Hello John,

Your order contains:
- Coffee
- Bagel
- Orange Juice

Thank you for your purchase!

You can see the exact output in the screenshot below:

ts multiline string

Check out Check If a String Is in an Enum in TypeScript

Alternative Method: String Concatenation with Line Breaks

Before template literals existed, we had to use string concatenation with explicit line breaks. Here is the complete code to create a multiline string in TypeScript.

let multilineString = "This is a string\n" +
                     "that spans across\n" +
                     "multiple lines.";

console.log(multilineString);

This method works, but it’s less readable and more error-prone than template literals. I only recommend this approach if you’re working with very old TypeScript configurations that don’t support ES6 features.

Using Array Join() Method

Another approach is to create an array of strings and join them with newline characters. This is another approach to creating multiline strings in TypeScript. Follow the code below:

let multilineString = [
    "This is a string",
    "that spans across",
    "multiple lines."
].join('\n');

console.log(multilineString);

This method can be useful when you’re programmatically building strings from multiple sources or when working with lists that need to be converted to multiline text.

Here is the exact output in the screenshot below:

multiline string typescript

Check out Array.find() in TypeScript

Working with Indentation in Multiline Strings

One challenge with template literals is managing indentation. The indentation in your code becomes part of the string:

function getTemplate() {
    return `
        <div>
            <h1>Hello World</h1>
            <p>This is a paragraph</p>
        </div>
    `;
}

console.log(getTemplate());

This will include all the spaces used for code indentation in the actual string. When working with HTML or other formats where whitespace matters, this can be problematic.

Solution: String Trimming Functions

A common approach is to create a helper function that removes the extra indentation:

function dedent(strings: TemplateStringsArray, ...values: any[]) {
    let result = strings.reduce((acc, str, i) => {
        return acc + str + (values[i] || '');
    }, '');

    // Find the common indentation
    const match = result.match(/^[ \t]*(?=\S)/gm);
    if (!match) return result;

    const indent = Math.min(...match.map(x => x.length));
    const dedented = result.replace(new RegExp(`^[ \\t]{${indent}}`, 'gm'), '');

    return dedented.trim();
}

const html = dedent`
    <div>
        <h1>Hello World</h1>
        <p>This is a paragraph</p>
    </div>
`;

console.log(html);

This function removes the common leading whitespace from each line, preserving the relative indentation while eliminating the extra spaces added for code readability.

Check out Convert String to Enum in TypeScript

Multiline Strings in TypeScript JSX/TSX

If you’re working with React in TypeScript (using .tsx files), there’s a specific consideration for multiline strings within JSX. Here is an example.

I provided this example because I know many professionals work with React using TypeScript.

function Component() {
    return (
        <div>
            {`This is a multiline
            string inside JSX.
            It preserves line breaks.`}
        </div>
    );
}

When rendering multiline content in JSX, template literals work well, but be aware that all whitespace (including indentation) is preserved.

Performance Considerations

All the methods I’ve discussed have similar performance characteristics for most applications. However, when working with very large strings or in performance-critical code:

  • Template literals have optimization in modern JavaScript engines
  • String concatenation with + can be less efficient for many concatenations
  • The array join() method is generally efficient for combining many strings

For most day-to-day TypeScript development, template literals should be your default choice based on readability alone.

Check out Convert String to Number in TypeScript

Best Practices for TypeScript Multiline Strings

After years of working with TypeScript, here are my recommendations:

  1. Use template literals as your default approach for multiline strings
  2. Create helper functions for specialized formatting needs
  3. Be mindful of indentation when working with formats where whitespace matters
  4. Consider extracting very long strings to separate files for better maintainability
  5. Use string interpolation instead of concatenation when embedding values

I hope you found this article helpful for handling multiline strings in TypeScript. Template literals have greatly simplified what used to be a common pain point in JavaScript and TypeScript development.

If you have any questions or suggestions about working with multiline strings in TypeScript, please leave them in the comments below.

Other TypeScript articles you may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App