DEV Community

Mathias Nielsen
Mathias Nielsen

Posted on

TIL about specific Array combination types

Okay, so its not actually called "specific Array combination types", but that was the best description I had for it, before I looked it up.
Its actually called "Tuple Types" and the documentation can be found here: https://www.tutorialsteacher.com/typescript/typescript-tuple

I'll come back to why this blew my mind today, but first, lets scroll back a bit, to some of my first steps into JS/TS programming. I started my programming career in Java, and one of the things that annoyed the hell out of me, was the fact that I could only have 1 object returned from a function (This was before the Pair class was introduced).

But in JS we can easily just return an array with 2 values:

const someFunction = () => {
    return ['Mathias', 28];
}
Enter fullscreen mode Exit fullscreen mode

And combined with some destructuring on the recieving, it was all nice and easy:

const [myName, myAge] = someFunction();
Enter fullscreen mode Exit fullscreen mode

Adding types

Until today I never had to add types onto a scenario like this, usually when I work with arrays, I either just do a basic string[], or when its required in complex object scenarios: Array<{name: string, age: number}>.
But with the tuples we can actually avoid naming them and just say the return type for our function is [string, number]:

const someFunction = (): [string, number] => {
    return ['Mathias', 28];
}
Enter fullscreen mode Exit fullscreen mode

Vue relation

I came across this when I working with Vue2 combined with TS, and was trying to create a v-for loop over a Map, but Vue2 did not support this, so I had to come up with a different approach that supported the same end goal.

So this is where the new tuples came in handy! Given an example with some data in a Map:

const map = new Map<string, object>();
map.set('key1', {data: 'lots of data'});
map.set('key2', {data: 'more data'});
Enter fullscreen mode Exit fullscreen mode

I could then destructure it into an array like so:

const asArray = ...map.entries();
// Yielding:
[
    ['key1', {data: 'lots of data'}],
    ['key2', {data: 'more data'}],
]
Enter fullscreen mode Exit fullscreen mode

And in order to Type this we now have:

const asArray: Array<[string, object]> = ...map.entries();
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this far, hope you gained something from this post.

Top comments (0)