DEV Community

Cover image for Typescript Series - Array Unshift Type
Sarmun Bustillo
Sarmun Bustillo

Posted on

Typescript Series - Array Unshift Type

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

Let's create a type for the JavaScript Array.unshift function. Which takes pushes an element into the array in the last position.

Unshift<[1, 2], 0> // [0, 1, 2,]
Unshift<['1', 2, '3'], boolean> \\ [boolean, '1', 2, '3']
Enter fullscreen mode Exit fullscreen mode

So we know we have an array and our type should return the new value + array.

type Unshift<TArray extends unknown[], U> = [U, ...TArray]
Enter fullscreen mode Exit fullscreen mode

TArray extends readonly unknown[] We first check our TArray is of type array.

Then we pass the value and we spread the array into an array [U, ...TArray]

Thank you!

you can find me here My Twitter

Top comments (0)