Object Spread
Learn about object spread and how to leverage it in TypeScript for cleaner and more efficient code.
We'll cover the following...
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 namevar firstObj = { id: 1, name: "firstObj" };// Copy the properties of firstObj to secondObj using object spread syntaxvar secondObj = { ...firstObj };// Log the secondObj to the consoleconsole.log(`secondObj : ${JSON.stringify(secondObj)}`);
-
We define a variable named
firstObj
on line 2 that is of typeobject
and has anid
property and aname
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 thefirstObj
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 ...