Typescript Series - Array Concat Type

sarmunbustillo

Sarmun Bustillo

Posted on August 23, 2022

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

💖 💪 🙅 🚩
sarmunbustillo
Sarmun Bustillo

Posted on August 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related