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.
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,
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'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.
We've already seen arrays being spread to form new arrays, so below we demonstrate spreading a string, a
Set, and a
For more on using
Map with TypeScript, see the section on the
lib compiler option in the Compiler Options chapter.