TypeScript Type Challenge Push Walkthrough

| 1 min read

The goal of this challenge is to implement a generic Push type that works like the built in Array.prototype.push 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 appended onto the array.

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

Watch the video

Coming soon

An example case

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

 Push<[], 1> // [1]
Push<[1, 2], '3'> // [1, 2, '3']
Push<['1', 2, '3'], boolean> // ['1', 2, '3', boolean]


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

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

We'd create a function that accepts two parameters, then we'd return a new array containing everything in a, followed by b, 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 Push<T extends unknown[], U> = ??

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

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