DEV Community

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

Posted on

Typescript Series - Array Concat 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.concat function. A type takes the two arguments. The output should be a new array that includes inputs in ltr order.

Some examples:

Concat<[], []>
// []

Concat<[], [1]>
// [1]

Concat<[1, 2], [3, 4]>,
// [1, 2, 3, 4]

Concat<['1', 2, '3'], [false, boolean, '4']>
// ['1', 2, '3', false, boolean, '4']
Enter fullscreen mode Exit fullscreen mode

So we know that our inputs should be arrays as well as the return type.

type Concat<T extends unknown[], U extends unknown[]> = [...T,... U]
Enter fullscreen mode Exit fullscreen mode

<T extends unknown[], U extends unknown[]> We first check if both of our inputs are arrays. If so, using the spread operator we spread both input values into a new array [...T,... U].

And there you go, our concat type is done.

Thank you!

you can find me here My Twitter

Top comments (0)