Array Concatenation


Problem - On Github

The aim for this challenge is to take two arrays and merges them together, placing the first arrays values first, followed by the second arrays values.

The initial type is:

type Concat<T, U> = any

Solution

Thinking about how you would implement this is Javascript gives you a great idea on how you may do this in Typescript. In ES6 the spread operator was added to Javascript which has a range of usages, but we want to look at the Array usage in this case.

If you spread an array into another array it will create a copy of the original.

[...originalArray] // Clone the array

If you spread multiple arrays into an array it will create an array with all the elements of the spread arrays.

// Combine two arrays into a new one
[...originalArrayOne, ...originalArrayTwo]

Turns out Typescript allows the same thing to happen with array types. So lets make sure T and U are arrays, and then we can spread them together into a new combined array. I will also create an any array type to keep things DRY, then use that type to create out concat type.

type AnyArray = any[];
type Concat<
    T extends AnyArray,
    U extends AnyArray
> = [...T, ...U]; // Spread the two types together


What to read more? Check out more posts below!