Open In App

Find the Length Tuple in TypeScript ?

In TypeScript, a Tuple is the data structure that allows storing a fixed number of elements of different types in a specific order. We can find the length of a tuple using various approaches that are implemented in this article in terms of examples.

There are several approaches available in TypeScript for finding the length of a tuple which are as follows:

Using the length property

In this approach, we are using the length property directly on the tuple variable to obtain its length, which counts the number of elements in the tuple.

Syntax:

tuple.length 

Example: The below example uses the length property to find the length of a dictionary in TypeScript.

let tuple: [number, string, boolean] = [2009, "GFG", true];
let tupleLength = tuple.length;
console.log("Tuple Length:", tupleLength);

Output:

"Tuple Length:",  3 

Using a for...in loop

In this approach, we are using a for...in loop to iterate through the tuple and increment a counter variable (tupleLength) for each element encountered, effectively counting the number of elements in the tuple.

Syntax:

for (variable in object) {
 // code 

Example: The below example uses the for…in loop to find the length of a tuple in TypeScript.

let tuple: [number, string, boolean] = [2009, "GFG", true];
let tupleLength = 0;
for (let _ in tuple) {
    tupleLength++;
}
console.log("Tuple Length:", tupleLength);


Output:

"Tuple Length:",  3 

Using the reduce method

In this approach, we are using the reduce method to accumulate the length of the tuple by adding 1 to the accumulator (acc) for each element encountered during the reduction process.

Syntax:

array.reduce(callback: (accumulator: T, currentValue: T, currentIndex: 
number, array: T[]) => T, initialValue?: T): T;

Example: The below example uses the reduce function to find the length of a tuple in TypeScript.

let tuple: [number, string, boolean] = [2009, "GFG", true];
let tupleLength = tuple
    .reduce((acc: number, curr: any) => acc + 1, 0);
console.log("Tuple Length:", tupleLength);


Output:

"Tuple Length:",  3 
Article Tags :