String Concatenation in TypeScript

While working on a TypeScript project, there are many situations where you’ll need to combine multiple strings to form a single message. For example, suppose you’re building a machine monitoring system. You might want to display something like: “Machine: Generator – Status: Operational”

For this requirement, we can perform string concatenation. TypeScript offers multiple ways to join strings, including the ‘+‘ operator, template literals, and string methods.

In this tutorial, we’ll learn about the efficient ways of string concatenation in TypeScript, with the help of real-time examples.

Concatenate Strings in TypeScript

In the methods below, we will learn several practical ways to concatenate strings in TypeScript.

Using the Plus (+) Operator

The plus operator is the most straightforward way to combine strings in TypeScript.

let firstName: string = "John";
let lastName: string = "Smith";
let fullName: string = firstName + " " + lastName;

console.log(fullName); // Output: John Smith

Output:

String Concatenation in TypeScript

I find this method particularly useful for simple concatenations. It’s readable and intuitive, especially for developers coming from other programming languages.

Check out: Convert a Number to a String in TypeScript

However, when concatenating multiple strings, the code can become less readable:

let street: string = "123 Main St";
let city: string = "New York";
let state: string = "NY";
let zipCode: string = "10001";

let address: string = street + ", " + city + ", " + state + " " + zipCode;

Using Template Literals (String Interpolation)

For more complex string concatenations, I prefer using template literals. They make the code more readable and allow for multi-line strings.

let firstName: string = "John";
let lastName: string = "Smith";
let fullName: string = `${firstName} ${lastName}`;

console.log(fullName); // Output: John Smith

Output:

TypeScript String Concatenation

Check out: Convert a String to Boolean in TypeScript

The example with the address becomes much cleaner:

let street: string = "123 Main St";
let city: string = "New York";
let state: string = "NY";
let zipCode: string = "10001";

let address: string = `${street}, ${city}, ${state} ${zipCode}`;

One thing I love about template literals is that they allow for expressions inside the ${} placeholders:

let price: number = 19.99;
let taxRate: number = 0.08;
let total: string = `Total: $${(price + (price * taxRate)).toFixed(2)}`;

console.log(total); // Output: Total: $21.59

Output:

Template Literals in TypeScript String Concatenation

Using the concat() Method

The string concat() method is another option for string concatenation:

let firstName: string = "John";
let lastName: string = "Smith";
let fullName: string = firstName.concat(" ", lastName);

console.log(fullName); // Output: John Smith

Output:

Concat string method in TypeScript

You can chain multiple concat() calls or pass multiple arguments:

let greeting: string = "Hello";
let name: string = "Sarah";
let message: string = greeting.concat(", ", name, "! Welcome to our website.");

console.log(message); // Output: Hello, Sarah! Welcome to our website.

Check out: Split a String by Comma in TypeScript

Using join() for Array Elements

When I’m working with an array of strings that need to be combined, the join() method is my go-to solution:

let machines: string[] = ["Lathe", "Drill Press", "CNC Machine"];
let machineList: string = machines.join(", ");

console.log(machineList); // Output: Lathe, Drill Press, CNC Machine

Output:

TypeScript Array String Concate

This is particularly useful for creating comma-separated lists, URLs, or paths:

let pathSegments: string[] = ["users", "profile", "settings"];
let url: string = "https://example.com/".concat(pathSegments.join("/"));

console.log(url); // Output: https://example.com/users/profile/settings

Output:

Use join to concate Strings in TypeScript

String Concatenation in Loops

Often, I need to build strings dynamically in loops. Here’s how I typically approach this:

let states: string[] = ["California", "Texas", "Florida", "New York"];
let statesList: string = "";

for (let i = 0; i < states.length; i++) {
    if (i > 0) {
        statesList += ", ";
    }
    statesList += states[i];
}

console.log(statesList); // Output: California, Texas, Florida, New York

Output:

TypeScript String Concatenation in loop

Check out: Remove a Substring from a String in TypeScript

For better performance with large strings, I recommend using an array and joining at the end:

let cities: string[] = ["Chicago", "Los Angeles", "Miami", "Boston"];
let citiesParts: string[] = [];

for (let city of cities) {
    citiesParts.push(city);
}

let citiesList: string = citiesParts.join(", ");
console.log(citiesList); // Output: Chicago, Los Angeles, Miami, Boston

Output:

TypeScript String Concatenation using Join

Check out:  Reverse a String in TypeScript

TypeScript Type Safety with String Concatenation

One of the benefits of TypeScript is its type safety. When concatenating strings with other types, TypeScript automatically converts them to strings:

let name: string = "John";
let age: number = 30;
let message: string = name + " is " + age + " years old.";

console.log(message); // Output: John is 30 years old.

Output:

Type Safety in TypeScript String Concatenation

However, it’s important to be explicit when you’re working with user input or data from external sources:

function createUserGreeting(user: { name?: string }): string {
    // Using the nullish coalescing operator for safe concatenation
    const userName = user.name ?? "Guest";
    return `Welcome, ${userName}!`;
}

console.log(createUserGreeting({ name: "Alice" })); // Output: Welcome, Alice!
console.log(createUserGreeting({})); // Output: Welcome, Guest!

Output:

TypeScript String Concatenation from input

Check out: Convert TypeScript Enum to String

Performance Considerations

When working with large strings or in performance-critical applications, it’s worth considering which method to use:

  1. Template literals are generally the most readable and maintainable option.
  2. For building strings in loops, using an array with join() is usually more efficient than repeatedly concatenating with the + operator.
  3. The concat() method can be slightly slower than the + operator in some browsers.

For most applications, the difference is negligible, so I recommend choosing the method that makes your code most readable.

Real-World Example: Building a Dynamic Query String

Let’s look at a practical example of string concatenation – building a query string for a weather API:

interface WeatherQueryParams {
    city: string;
    state?: string;
    units?: 'imperial' | 'metric';
    days?: number;
}

function buildWeatherApiUrl(baseUrl: string, params: WeatherQueryParams): string {
    const queryParts: string[] = [];

    // Add required parameters
    queryParts.push(`city=${encodeURIComponent(params.city)}`);

    // Add optional parameters if they exist
    if (params.state) {
        queryParts.push(`state=${encodeURIComponent(params.state)}`);
    }

    if (params.units) {
        queryParts.push(`units=${params.units}`);
    }

    if (params.days && params.days > 0) {
        queryParts.push(`forecast_days=${params.days}`);
    }

    // Build the final URL
    return `${baseUrl}?${queryParts.join('&')}`;
}

const weatherUrl = buildWeatherApiUrl(
    'https://api.weather.example.com/forecast',
    {
        city: 'San Francisco',
        state: 'CA',
        units: 'imperial',
        days: 5
    }
);

console.log(weatherUrl);
// Output: https://api.weather.example.com/forecast?city=San%20Francisco&state=CA&units=imperial&forecast_days=5

Output:

Query String Concatenation in TypeScript

In this example, I’m using template literals for the overall structure and the array join() method for building the query string parts – a perfect combination of readability and performance.

String concatenation in TypeScript offers several approaches, each with its own advantages. For most cases, I recommend using template literals for their readability and flexibility. For performance-critical code or when working with arrays, the array join method is an excellent choice.

Check out: Create Multiline Strings in TypeScript

Conclusion

In this TypeScript tutorial, we’ve learned how to handle string concatenation in TypeScript using different approaches based on real-world scenarios. We started with the basic + operator to concatenate for simple string combinations. We then learned about template literals, which offer cleaner syntax and improved readability, especially when working with multiple variables or expressions.

For array-based concatenation, we used the join() method, which is useful for building lists, paths, or query strings.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.