Explain the Tuple Types in TypeScript
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:
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.
[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.
Note: As tuple is a form of array, we can easily use functions applicable to an array, like concat, map etc, on a tuple