Spread Operator#

The spread operator faciliates three common tasks:

  • Copying the elements of one or more arrays into a new array

  • Copying the properties of one or more objects into a new object

  • Spreading an array when calling a function, where the function only accepts a comma-separated list of arguments

ES2015 introduced spreading for arrays and function calls. ES2018 introduced spreading for objects. Both specifications are supported in TypeScript.

In this section we cover spreading arrays and objects as well as spreading arrays when calling functions.

Spreading Arrays#

When spreading an array, all of the elements in the array will be copied into the new array. If we have multiple arrays that we want to combine, we can use the spread operator to combine them to form a new array.

In the example below, we have two arrays, firstArr and secondArr, that we combine to form a new array:

The elements of thirdArr are dependent on the order that we spread the arrays in the array literal. If we spread secondArr before firstArr, secondArr's elements will be placed before firstArr in the resulting array.

Spreading an empty array is allowed, but has no effect on the output:

Thus far, we have made it seem as if only arrays can be spread. In reality, spreading is not exclusive to arrays. Any iterable object can be spread over an array.

An iterable is a JavaScript object that conforms to the iterator protocol, which was introduced in ES2015 as a way for objects to specify iteration behavior for cases like spreading and for..of loops. Array, String, Map, and Set (the constructors for the corresponding JavaScript values) all implement the iterator protocol, meaning we can use them when spreading to arrays.

We've already seen arrays being spread to form new arrays, so below we demonstrate spreading a string, a Set, and a Map:

For more on using Set and Map with TypeScript, see the section on the lib compiler option in the Compiler Options chapter.

 

This page is a preview of Beginners Guide to TypeScript

Start a new discussion. All notification go to the author.