Borislav Hadzhiev
Wed Mar 09 2022·2 min read
Photo by Carlos
Use the spread syntax to merge arrays in TypeScript, e.g.
const arr3 = [...arr1, ...arr2]
. The spread syntax will unpack the values of
the arrays into a new array. The final array will have a type that reflects the
types of the values in the supplied arrays.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; // 👇️ const arr3: string[] const arr3 = [...arr1, ...arr2];
We used the spread syntax (...) to unpack the elements of 2 arrays into a third array.
The type of the final array will reflect the type of the provided arrays.
const arr1 = ['a', 'b']; const arr2 = [1, 2]; // 👇️ const arr3: (string | number)[] const arr3 = [...arr1, ...arr2]; // 👇️ ['a', 'b', 1, 2] console.log(arr3);
We used the spread syntax (...) to unpack a string and number arrays into a third array.
The type of the third array is a union representing an array of strings and numbers.
When using the spread syntax, the order in which you unpack the arrays is important.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; // 👇️ const arr3: string[] const arr3 = [...arr2, ...arr1]; // 👇️ ['c', 'd', 'a', 'b'] console.log(arr3);
This process can be repeated with as many arrays as necessary.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = ['e', 'f']; // 👇️ const arr3: string[] const arr4 = [...arr1, ...arr2, ...arr3]; // 👇️ ['a', 'b', 'c,' 'd', 'e', 'f'] console.log(arr4);
You might also see the Array.concat method being used to merge arrays in TypeScript.
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; const arr3 = ['e', 'f']; // 👇️ const arr3: string[] const arr4 = arr1.concat(arr2, arr3); // 👇️ ['a', 'b', 'c,' 'd', 'e', 'f'] console.log(arr4);
The concat
method also merges two or more arrays. The method takes one or more
arrays as parameters and merges them into the array on which it was called.
However, you should stick to using the spread syntax (...), because the typings
for the concat
method in TypeScript are not as intuitive.
const arr1 = ['a', 'b']; const arr2 = [1, 2]; // ⛔️ Type 'number[]' is not assignable to // type 'ConcatArray<string>'.ts(2769) const arr3 = arr1.concat(arr2);
The example above causes the type checker to throw an error, because we called
the concat()
method on an array of strings and passed it an array of numbers.
This is not the case when working with the spread syntax (...), which is much more flexible.