Typescript Series - Array Concat Type
Sarmun Bustillo
Posted on August 23, 2022
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']
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]
<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
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
November 17, 2023