TypeScript Type Challenge Unshift Walkthrough

| 1 min read

The goal of this challenge is to implement a generic Unshift type that works like the built in Array.prototype.unshift javascript method. It should take two arguments, the first an array and the second any. It should return a new type with the second element prepended onto the start of the array.

The challenge: https://github.com/type-challenges/type-challenges/blob/main/questions/03060-easy-unshift/README.md

Watch the video

Coming soon

An example case

For example, given the following cases, our Unshift type should return the type shown in the comments:

 Unshift<[], 1> // [1]
Unshift<[1, 2], 0> // [0, 1, 2]
Unshift<['1', 2, '3'], boolean> // [boolean, '1', 2, '3']

Approach

This challenge is very similar to the Push challenge and Concat challenge. So again, if we were to solve this challenge with modern runtime javascript without using the built in unshift methods, the solution would be very simple:

function unshift(t, u) {
return [u, ...t];
}

We'd create a function that accepts two parameters, then we'd return a new array containing u, followed by everything in a, by spreading the contents of a.

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 an array and an any:

  type Unshift<T extends unknown[], U> = ??

We'll then use the spread operator to return a new type with U, followed by all elements from T:

  type Unshift<T extends unknown[], U> = [U, ...T]