I recently made a small utility for converting an array to an object. I was exploring the syntax for the 2-dimensional array and wanted to investigate when a tuple was a better data structure.
In my utility code below, I originally structured the array parameter as a 2-dimensional array. However, in this case I always want exactly two elements in each entry of the inner array. I always want both elements to be strings. Since I am precise about both the length of each item in the inner array and about the type of each item in the inner array, this is exactly the time to use a tuple.
export const twoDimArrayToObject = function(array: string[][]) {
const returnObject: {
[key: string]: string
} = {};
array.forEach((element) => {
returnObject[element[0]] = element[1];
})
return returnObject;
}
What’s the Difference?
Tuples are similar to arrays but more precise. Tuples have a precise number of elements (disregarding optional params). Tuples can also have a variety of types of elements, i.e. [string, number, string[]].
The New Code
Naturally, I typed the param as an array of tuples in the function declaration.
export const twoDimArrayToObject = function(array: [string, string][]) {
const returnObject: {
[key: string]: string
} = {};
array.forEach((element) => {
returnObject[element[0]] = element[1];
})
return returnObject;
}
Interestingly, I had to specifically tell the compiler that the value to be passed in was an array of tuples. The compiler tried to auto type it as string[][] and threw a compile time error.
const twoDimArray: [string, string][] = [ //had to type it here
['state', 'Texas'],
['county', 'Tarrant'],
['city', 'Ft. Worth']
]
console.log(twoDimArrayToObject(twoDimArray));
The output is the same with either typing strategy. However, choosing the proper type conveys your intentions to your teammates and anyone who maintains the code later.