Search⌘ K

The Spread Operator and Objects

Explore how to use the spread operator in TypeScript to create shallow copies of objects while maintaining immutability. Learn to add or override properties in cloned objects and understand its behavior with object literals versus class instances.

Simple copy

You can spread an object similar to an array. Spreading an object is handy in a scenario where you need to create a clone for immutability purposes or if you are already using the function Object.assign.

The assign method is similar in functionality but uses a more verbose syntax. The syntax for the spread operator is identical to the spread for an array which means that it uses the three dots in front of the object instead of the array.

To create a clone, you need to define a variable, open a curly bracket, a spread operator, the variable to copy, and close the curly bracket. It copies all members and makes them float side by side with a comma. Indeed, this is just a visualization to help you illustrate that the curly brackets take the result and form a new object.

In the following code, line 2 is performing the object clone. Notice the curly brackets ...