We know that an array holds multiple values of the same data type. But sometimes, we may need to store a collection of values of different data types in a single variable. Arrays will not provide this feature, but TypeScript has a data type called Tuple to achieve this purpose. A Tuple is an array which store multiple fields belong to different data types. It is similar to the structures in the C programming language.
A tuple is a data type which can be used like any other variables. It represents the heterogeneous collection of values and can also be passed as parameters in a function call.
[101, 'JavaTpoint', 105, 'Abhishek']
We can also declare and initialize a tuple separately by initially declaring the tuple as an empty tuple in Typescript.
Accessing tuple Elements
We can read or access the fields of a tuple by using the index, which is the same as an array. In Tuple, the index starts from zero.
Name of the Employee is: Rohit Sharma Age of the Employee is: 25 Rohit Sharma is working in JavaTpoint
Operations on Tuple
A tuple has two operations:
The push operation is used to add an element to the tuple.
Items: Rohit Sharma, 25, JavaTpoint Length of Tuple Items before push: 3 Length of Tuple Items after push: 4 Items: Rohit Sharma, 25, JavaTpoint, 10001
The pop operation is used to remove an element from the tuple.
Items: Rohit Sharma,25, JavaTpoint, 10001 Length of Tuple Items before pop: 4 Length of Tuple Items after pop: 3 Items: Rohit Sharma, 25, JavaTpoint
Update or Modify the Tuple Elements
Tuples are mutable, which means we can update or change the values of tuple elements. To modify the fields of a Tuple, we need to use the index of the fields and assignment operator. We can understand it with the following example.
Name of the Employee is: Rohit Sharma Age of the Employee is: 30 Rohit Sharma is working in JavaTpoint
Clear the fields of a Tuple
We cannot delete the tuple variable, but its fields could be cleared. To clear the fields of a tuple, assign it with an empty set of tuple field, which is shown in the following example.
Destructuring the Tuple
Destructuring allows us to break up the structure of an entity. TypeScript used destructuring in the context of a tuple.
Rohit Sharma 25
Passing Tuple to Functions
We can pass a tuple to functions, which can be shown in the below example.
JavaTpoint 101 Abhishek