DEV Community

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

Posted on

Typescript Series - Array Push 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.push function. Which takes pushes an element into the array in the last position.

Push<[1, 2], '3'> // [1, 2, '3']
Push<['1', 2, '3'], boolean> // ['1', 2, '3', boolean]
Enter fullscreen mode Exit fullscreen mode

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

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

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

then we simply spread the array and the new value into an array [...TArray, U]

Thank you!

you can find me here My Twitter

Top comments (0)