Tuple destructuring

As tuples use the array syntax, they can be destructured, or disassembled, in two ways. The first is by means of simple array syntax as follows:

console.log(`tupleType[0] : ${tupleType[0]}`); 
console.log(`tupleType[1] : ${tupleType[1]}`); 

Here, we are simply logging each property of the tupleType variable to the console by referencing its index within the array, that is, tupleType[0] and typleType[1]. The output of this code would be as follows:

tupleType[0] : test
tupleType[1] : false

So we have now created a tuple with a string and boolean value, and destructured it with array syntax. Note that because we are using array syntax, we are able to interrogate the third property of this tuple as follows:

console.log(`tupleType[2] : ${tupleType[2]}`); 

As our tuple does not have a third property, typleType[2] will be undefined, as can be seen in the output of this line of code:

tupleType[2] : undefined

This is obviously not ideal.

A better way of destructuring a tuple is to use the array syntax to create a matching tuple on the left-hand side of the assignment, as follows:

let [t1, t2] = tupleType; 
console.log(`t1: ${t1}`); 
console.log(`t2: ${t2}`); 

Here, we are defining an array of two elements, named t1 and t2, and assigning the value of the tuple to this array. We then log both t1 and t2 to the console. The output of this code is as follows:

t1: test
t2: false

This method of destructuring a tuple is preferred for a simple reason. We cannot define an array of elements that exceeds the number of properties in a tuple. Hence, the following code would not work:

let [et1, et2, et3] = tupleType; 

Here, we are attempting to destructure our two-property tuple into a three-property tuple. The compiler, in this case, will generate the following error:

error TS2493: Tuple type '[string, boolean]' with length '2' cannot be assigned to tuple with length '3'