Push And Unshift


Problem - Push On Github - Unshift On Github

Push and unshift are very similar problems in typescript. The aim of both is to add an element to the array - it just changes which side the element is added. For push the element will be added to the end, and for unshift it will be added to the beginning.

The initial types are:

type Push<T, U> = any;
type Unshift<T, U> = any;

Solution

The solution for this problem is almost identical to the Array Concatenation problem. In that problem two arrays were spread together into a single new array type.

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

This time we only need to spread the initial array, and then add the new element to either the start or end.

// Add `U` to the end of the array
type Push<T extends any[], U> = [...T, U];

// Add `U` to the start of the array
type Unshift<T extends any[], U> = [U, ...T];


What to read more? Check out more posts below!