How to Use Spread Operator in TypeScript?

Recently, I was working on a complex TypeScript project where I needed to combine multiple arrays and objects. The challenge was to do this without making changes to the original data structure.

While searching for a solution, I came to know about the Spread Operator. Using this, I was able to combine arrays, copy objects, pass function arguments easily, and even conditionally add properties.

In this article, I’ll explain the TypeScript spread operator, from basic usage to advanced techniques.

What is the Spread Operator in TypeScript?

The spread operator (denoted by three dots ) is a powerful feature in TypeScript that allows you to expand elements from an iterable (like an array) or properties from an object into another array or object.

It’s one of those features that once you start using, you’ll wonder how you ever coded without it.

Spread Operator with Arrays

Method 1: Combining Arrays

One of the most common uses of the spread operator is combining arrays:

// Combining two arrays of US states
const northeastStates = ['New York', 'Massachusetts', 'Connecticut'];
const southeastStates = ['Florida', 'Georgia', 'North Carolina'];

// Using spread operator to combine arrays
const eastCoastStates = [...northeastStates, ...southeastStates];

console.log(eastCoastStates);
// Output: ['New York', 'Massachusetts', 'Connecticut', 'Florida', 'Georgia', 'North Carolina']

Output:

Spread Operator in TypeScript

Check out: Nullish Coalescing (??) vs Logical OR (||) Operator in TypeScript

Method 2: Creating Array Copies

The spread operator creates a shallow copy of an array, which is perfect when you need to work with a copy without modifying the original:

// Original array of US cities
const majorCities = ['New York', 'Los Angeles', 'Chicago', 'Houston'];

// Creating a copy with spread operator
const citiesCopy = [...majorCities];

// Modifying the copy won't affect the original
citiesCopy.push('Phoenix');
console.log(majorCities); // Original remains unchanged
console.log(citiesCopy);  // Has the additional city

Output:

Use Spread operator to copy array in TypeScript

Method 3: Adding Elements to Arrays

You can elegantly add elements at the beginning, middle, or end of an array:

const westernStates = ['California', 'Oregon', 'Washington'];

// Adding at the beginning
const withAlaska = ['Alaska', ...westernStates];

// Adding at the end
const withHawaii = [...westernStates, 'Hawaii'];

// Adding in the middle
const withNevada = [...westernStates.slice(0, 1), 'Nevada', ...westernStates.slice(1)];

Spread Operator with Objects

Method 1: Merging Objects

Similar to arrays, you can merge objects together:

// User profile information
const basicInfo = {
  firstName: 'John',
  lastName: 'Smith',
  email: 'john.smith@example.com'
};

// Additional information
const addressInfo = {
  street: '123 Main St',
  city: 'New York',
  state: 'NY',
  zipCode: '10001'
};

// Merge to create complete profile
const completeProfile = { ...basicInfo, ...addressInfo };

console.log(completeProfile);
// Output includes all properties from both objects

Output:

Spread Operator in TypeScript Objects

Check out: Double Question Mark (??) Operator in TypeScript

Method 2: Overriding Properties

The spread operator is perfect for creating new objects with some modified properties:

const userSettings = {
  theme: 'light',
  notifications: true,
  fontSize: 14
};

// Create new settings object with dark theme
const darkModeSettings = { 
  ...userSettings, 
  theme: 'dark' 
};

console.log(darkModeSettings);
// Output: { theme: 'dark', notifications: true, fontSize: 14 }

Output:

Override properties using Spread Operator in TypeScript

Method 3: Adding New Properties

You can also add new properties while preserving the original:

const product = {
  id: 'prod-1234',
  name: 'Smartphone',
  price: 699
};

// Add discount information
const discountedProduct = {
  ...product,
  discountPercentage: 15,
  discountedPrice: product.price * 0.85
};

Check out: Mapped Types in TypeScript

Advanced Spread Operator Techniques

Working with Function Arguments

The spread operator can be used to pass array elements as arguments to a function:

function calculateTotalSales(northeast: number, southeast: number, midwest: number, west: number): number {
  return northeast + southeast + midwest + west;
}

// Define as a tuple with 4 elements
const regionalSales: [number, number, number, number] = [1200000, 950000, 850000, 1500000];

const totalSales = calculateTotalSales(...regionalSales);
console.log(`Total company sales: $${totalSales}`);

Output:

Override properties using Spread Operator in TypeScript

Combining Spread with Rest Parameters

You can use spread with rest parameters to create powerful function patterns:

const todaysOrders = ['A12345', 'B67890', 'C13579', 'D24680'] as [string, ...string[]];

function processOrders(firstOrder: string, ...remainingOrders: string[]) {
  console.log(`Priority processing: ${firstOrder}`);
  console.log(`Batch processing: ${remainingOrders.join(', ')}`);
}

processOrders(...todaysOrders);

Output:

Combine Spread with Rest Parameter in TypeScript

Conditional Spreading with TypeScript

TypeScript allows you to conditionally include properties, which is excellent for configuration objects:

interface AppConfig {
  apiUrl: string;
  timeout: number;
  debug?: boolean;
  analytics?: boolean;
}

const defaultConfig: AppConfig = {
  apiUrl: 'https://api.example.com',
  timeout: 3000
};

function createConfig(isDevelopment: boolean): AppConfig {
  const config = {
    ...defaultConfig,
    ...(isDevelopment ? { debug: true } : {}),
    ...(isDevelopment ? {} : { analytics: true })
  };

  console.log(`Generated ${isDevelopment ? 'development' : 'production'} config:`, config);
  return config;
}

const devConfig = createConfig(true);
const prodConfig = createConfig(false);

Output:

Conditional Spread operator in TypeScript

Check out: TypeScript Type Narrowing

TypeScript Type Safety with Spread

One of the great advantages of using TypeScript with the spread operator is type safety:

interface User {
  id: string;
  name: string;
  email: string;
}

interface UserWithAddress extends User {
  address: string;
  city: string;
  state: string;
  zipCode: string;
}

const basicUser: User = {
  id: 'user123',
  name: 'Jane Doe',
  email: 'jane.doe@example.com'
};

// TypeScript will error if required properties are missing
const completeUser: UserWithAddress = {
  ...basicUser,
  address: '456 Oak Ave',
  city: 'Chicago',
  state: 'IL',
  zipCode: '60601'
};

Output:

TypeScript Type Safety with Spread Operator

Conclusion

In this tutorial, we learned how the spread operator works in TypeScript and how it can help in different situations. We learned how to combine arrays, copy objects without changing the original, add or override properties, and even pass values into functions using the spread syntax.

The spread operator makes the code cleaner, more readable, and safer especially when working with TypeScript’s type system. Whether you’re dealing with UI data, API configs, or just organizing values in an app, using the spread operator is a simple way to manage it all.

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.