TypeScript Type Challenge Concat Walkthrough
The goal of this challenge is to implement a generic Concat type works like the built in Array.prototype.concat javascript method. It should take two array arguments and return a new type with elements from both arguments (in left to right order).
The challenge: https://github.com/type-challenges/type-challenges/blob/main/questions/00533-easy-concat/README.md
Watch the video
Coming soon
An example case
For example, given the following cases, our Concat type should return the type shown in the comments:
Concat<[], []> // []
Concat<[], [1]> // [1]
Concat<[1, 2], [3, 4]> // [1, 2, 3, 4]
Concat<['1', 2, '3'], [false, boolean, '4']>// ['1', 2, '3', false, boolean, '4']
Approach
If we were to solve this challenge with modern runtime javascript, the solution would be very simple:
function concat(t, u) {
return [...t, ...u];
}
We'd create a function that accepts two parameters, then we'd return a new array containing everything in t and u, by spreading both arrays.
We can do this exact thing in the type system using Variadic Tuple Types!
The solution
We'll start by implementing a type that accepts two arrays as generics:
type Concat<T extends unknown[], U extends unknown[]> = ??
We'll then use the spread operator to return a new type with all elements from T and U inside:
type Concat<T extends unknown[], U extends unknown[]> = [...T, ...U]