Javatpoint Logo
Javatpoint Logo

TypeScript Tuples

We know that an array holds multiple values of the same datatype. 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 datatype called tuple to achieve this purpose. A tuple is an array that store multiple fields belong to varied data types. They are just like structures in the C programming language.

A tuple is a data type that 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.

The term tuple is used in abstract mathematics to denote a multidimensional coordinate system.

JavaScript doesn't have tuples as data types, but TypeScript does.

The order of elements in a tuple is important. In Tuple, data needs to be imputed as initially declared.

Syntax

Example

Output:

[101, 'JavaTpoint', 105, 'Abhishek']

We can also declare and initialize a tuple separately by initially declaring the tuple as an empty tuple in Typescript.

Example

Accessing tuple Elements

We can read or access the fields of a tuple by using the index, which is the same as an array. An index starts from zero.

Example

Output:

Name of the Employee is : Rohit Sharma
Age of the Employee is : 25
Rohit Sharma is workinging in JavaTpoint

Operations on Tuple

A tuple has two operations:

  1. Push()
  2. Pop()

Push()

The push operation is used to add an element to the tuple.

Example

Output:

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 push operation is used to add an element to the tuple.

Example

Output:

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

To modify the fields of a Tuple, we need to use the index of the fields and assignment operator. It can be shown in the following example.

Example

Output:

Name of the Employee is: Rohit Sharma
Age of the Employee is: 30
Rohit Sharma is workinging 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 tuple field set as shown in the following.

Example

Output:

[]

Destructuring the Tuple

In TypeScript, Destructuring refers to breaking up the structure of an entity.

Example

Output:

Rohit Sharma
25

Passing Tuple to Functions

We can pass a tuple to functions which can be shown in the below example.

Example

Output:

JavaTpoint
101
Abhishek
Next TopicTypeScript Union




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA