Tuples in TypeScript

In the case of an array, we can not insert multiple file types as elements of the same array. So Type script introduced a tuple in which we can pass multiple data types like number string etc in the same tuple. The works of supply are the same as an array.

To declare a tuple first declare a variable and then after equal sign provides some data of mixture data type separated by coma surrounded by a square bracket.

Example of tuples:
var sample_tuple = [1,'aa','bb',2,3,4];
console.log(sample_tuple);

Access data from tuple

to access data from a tuple we have to write the property name of the tuple and then the index of the tuple inside a square bracket.

Example of access data from tuple
var sample_tuple = [1,'aa','bb',2,3,4];
console.log(sample_tuple[0]);
console.log(sample_tuple[1]);
console.log(sample_tuple[2]);
console.log(sample_tuple[3]);
console.log(sample_tuple[4]);

Operation of Tuple

Same as an array we can do many operations with tuple and they are as described below:

push(): we can push data at the end of the tuple using the push method. and the uses of the push method are the same as an array:

Example of push() method:
var sample_tuple = [1,'aa','bb',2,3,4];
sample_tuple.push('mnop');
console.log(sample_tuple);

pop(): same as array pop method used to remove the last item and returns the removed item.

Example of pop() method:
var sample_tuple = [1,'aa','bb',2,3,4];
var removed_item = sample_tuple.pop();
console.log(removed_item);

Update Tuple:

We can assign any value or update any value of a tuple referring to the index of the element. To use that we have to write the tuple name and then have to provide the index of the element inside the squire bracket and then have to assign a value after an equal sign.

Example of Update Touple:
var sample_tuple = [1,'aa','bb',2,3,4];
sample_tuple[2] = 'mnop';
console.log(sample_tuple);

Tuple destructuring:

Like an array, we can assign each value of a tuple in an individual variable and for that, we have to take an array and then have to declare a variable surrounded by a square bracket we have to declare some variable separated by coma and then have to assign the array property name after the equal sign.

Example of tuple destructuring:
var sample_tuple = [1,'aa'];
var [x,y] = sample_tuple;
console.log(x);
console.log(y);

Share The Post On -