How to use the Spread Operator (…) In Typescript

In this approach we are using the spread operator (…) to create a new array with the existing elements of the array and the new object.

Syntax:

let newArray = [...existingArray, newElement];

Example: This example uses Spread Operator to add Object to an Array in typescript.

JavaScript
let products: { name: string, price: number, category: string }[] =
    [
        {
            name: 'Laptop',
            price: 1000,
            category: 'Electronics'
        },
        {
            name: 'Headphones',
            price: 100,
            category: 'Electronics'
        }
    ];

let newProduct = {
    name: 'Smartphone',
    price: 800,
    category: 'Electronics'
};
let newProducts = [...products, newProduct];

console.log(newProducts);

Output:

[
{ name: 'Speaker', price: 1000, category: 'Electronics' },
{ name: 'Bluetooth', price: 800, category: 'Electronics' },
{ name: 'Smartwatch', price: 1500, category: 'Electronics' }
]

Add an Object to an Array in TypeScript

TypeScript allows adding an object to an array that is a common operation when working with collections of data.

Below are the approaches to add an object to an array in TypeScript:

Table of Content

  • Using the push method
  • Using the Spread Operator (…)
  • Using array concatenation (concat)
  • Using Array Unshift
  • Using Index Assignment:
  • Using Array splice() Method

Similar Reads

Using the push method

In this approach, we are using the push method which is used to add one or more elements to the end of an array....

Using the Spread Operator (…)

In this approach we are using the spread operator (…) to create a new array with the existing elements of the array and the new object....

Using array concatenation (concat)

In this approach we are using the concat method which is used to merge two or more arrays. It does not mutate the original arrays but returns a new array containing the elements of the original arrays....

Using Array Unshift

In this approach we are using the unshift method in TypeScript which is used to add a new object to the beginning of an array....

Using Index Assignment:

Using index assignment, you can directly assign an object to a specific index in an array in TypeScript. It adds the object to the array at the specified index, extending the array if necessary....

Using Array splice() Method

In this approach we are using splice method which can be used to add elements at a specific index. An object can only be added without deleting any other element by specifying the second parameter to 0....

Using Array splice() Method

The splice() method can be used to add elements at a specific index in an array. This method allows you to insert an object into an array at any position without deleting any other elements by specifying the second parameter as 0....