How to merge Arrays in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 9, 2022

banner

Photo from Unsplash

Merge Arrays in TypeScript #

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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
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.

index.ts
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.

The typings expect you to only pass arrays of the same type as parameters to the concat method.

This is not the case when working with the spread syntax (...), which is much more flexible.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.