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.
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