Open In App

Explain the Tuple Types in TypeScript

TypeScript is an Open Source Object Oriented programming language developed and maintained by Microsoft Corporation. TypeScript is a strongly typed language and its first version was introduced in 2012. It is a Strict Super Set of JavaScript, which means anything that is implemented in JavaScript can be implemented using TypeScript along with the choice of adding enhanced features (every existing JavaScript Code is a valid TypeScript Code)

In this article, we are going to look into the tuple data type in TypeScript.



Tuple: Tuple is a new data type introduced by TypeScript. Unlike array, tuples can have values of different data types. For example, in the code below we have a tuple with element types as boolean, string:

var geek: [boolean, string] = [true, "Aayush"];

We can also create tuples of multiple data types, like this one right here is a tuple of data types boolean, string and number.



var nice: [boolean, string, number] = [true, "Aayush", 1];

Accessing Tuple Elements: As a tuple is a form of an array, we can use indexing to access individual elements in a tuple, just the way I have done in the following code:

Example:




var geek: [boolean, string] = [true, "Aayush"];
console.log(geek[0]);
console.log(geek[1]);

Output:

true
"Aayush"

Add Elements into Tuple: The push() function allows you to add additional members to a tuple. Let us understand this by looking an example, in the following code we are pushing a string to the already created geek tuple.

Example:




var geek: [boolean, string] = [true, "Aayush"];
geek.push("hello");
console.log(geek)

Output:

[true, "Aayush", "hello"]

You might also be tempted to push something other than string or boolean into the tuple geek, however, this will lead to an error. For example, running the following code

var geek: [boolean, string] = [true, "Aayush"];
geek.push(20);
console.log(geek)

gives the following error:

Argument of type '20' is not assignable to parameter of type 'string | boolean'.

Remove Elements from Tuple: We can use the pop() function to remove the last element from the tuple.

Example:




var geek: [boolean, string] = [true, "Aayush"];
geek.pop();
console.log(geek)

Output:

[true] 

Note: As tuple is a form of array, we can easily use functions applicable to an array, like concat, map etc, on a tuple


Article Tags :