TypeScript plays a big part in making Angular a great framework. Part of the reason why it’s great is because it brings to the table a lot of features from ES2015 or even ES2017 that aren’t available yet for all browsers. Yet TypeScript allows us to use those features and transpiles them down to good old ES5 javascript, which runs great in all browsers.
Today I want to highlight one of those features: Object spread, which basically allows us to copy an entire object as a part of another object:
The above code turns copy
into a copy of the original
object. Easy enough, right?
Now let’s use the spread syntax to merge two objects together:
Note that when you use the spread operator, objects can have properties that have the same name. In that case, the last declaration wins, which translates into the following example:
In order to keep the value of name
for object b
, we would have to use the spread operator first, then declare name
as follows:
The spread operation can also be used to concatenate several objects into one:
As you can see, a lot of great things can be done with the spread operator. Next week I’ll show you that we can also use the three-dot syntax in another interesting way: Object rest.