...

/

Object Spread

Object Spread

Learn about object spread and how to leverage it in TypeScript for cleaner and more efficient code.

Introduction to object spread

When working with basic JavaScript objects, we often need to copy the properties of one object to another or do some mixing and matching of properties from various objects. In TypeScript, we can use an ES7 technique known as object spread to accomplish this.

Consider the following code:

// Define firstObj with properties id and name
var firstObj = { id: 1, name: "firstObj" };
// Copy the properties of firstObj to secondObj using object spread syntax
var secondObj = { ...firstObj };
// Log the secondObj to the console
console.log(`secondObj : ${JSON.stringify(secondObj)}`);
Cloning object properties with spread syntax
  • We define a variable named firstObj on line 2 that is of type object and has an id property and a name property.

  • We then define a variable named secondObj on line 5 and use the object spread syntax of three dots (...) to assign a value to it. The value we are assigning is an object that is made up of the firstObj variable, that is, { ...firstObj }.

When we run this code, we can see that the id and name properties and values have been copied into the new secondObj variable.

We can also use this ...