![]() |
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: Table of Content Using the length propertyIn this approach, we are using the Syntax:tuple.length Example: The below example uses the length property to find the length of a dictionary in TypeScript.
Output: "Tuple Length:", 3 Using a for…in loopIn 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) { Example: The below example uses the for…in loop to find the length of a tuple in TypeScript.
Output: "Tuple Length:", 3 Using the reduce methodIn 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: Example: The below example uses the reduce function to find the length of a tuple in TypeScript.
Output: "Tuple Length:", 3 Using TypeScript’s Type UtilitiesIn this approach, we will use TypeScript’s type utilities to determine the length of a tuple. This method leverages TypeScript’s type system to compute the length at compile time, ensuring type safety and potentially improving performance by avoiding runtime calculations. Syntax:type Length<T extends readonly any[]> = T['length']; Example: In this example we defines a Length type utility to extract the length of a tuple. It infers the length of the tuple tuple and prints it using tuple.length
Output: Tuple Length: 3 Using recursion:In this approach, we define a recursive function that iterates through the tuple and counts the elements until reaching the end of the tuple. Recursion allows us to traverse through each element of the tuple without needing to know its length beforehand. Example:
Output Tuple Length: 3 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |