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:
const firstArr = [1,2];
const secondArr = [4,5];
const thirdArr = [firstArr, secondArr, 5, 6];
console.log(thirdArr); // [1, 2, 3, 4, 5, 6];
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:
const myArr = [ , 1, 2, 3]; // [1, 2, 3]
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
const arrFromStr = ['Types']; // ['T', 'y', 'p', 'e', 's']
const arrFromMap = [new Map([ 'a', true ])]; // [['a', true]]
const arrFromSet = [new Set([1, 2, 3])]; // [1, 2, 3]
For more on using
Map with TypeScript, see the section on the
lib compiler option in the Compiler Options chapter.