TypeScript Tuples

In typescript, Tuples are capable to store different type of data elements. It can work on two or more data types. Internally similar to the tuple array. It is used to store multiple fields in a variable..

Tuple Declaration and Initialization

var student : [string,number] = ["Smith",21];
var month   : [number,string] = [1,"January"];
console.log(student);
console.log(month);
Define Tuple in TypeScript
[ 'Smith', 21 ]
[ 1, 'January' ]

The tuple element is used by the index position. Those who start from zero.

var student : [string,number] = ["Smith",21];
var month   : [number,string] = [1,"January"];
console.log(student[0]); // "Smith"
console.log(month[1]); // "January"

Tuple Array Elements

var result : [string,number,string][]; //Define Tuple Array
    
    result=[["Math",45,"Pass"],["Chemistry",20,"Fail"],["English",90,"Pass"]];
    
    console.log(result);
Tuple Array Elements
[ [ 'Math', 45, 'Pass' ],
[ 'Chemistry', 20, 'Fail' ],
[ 'English', 90, 'Pass' ] ]

Tuple Operations

Add Tuple Operations

push() method are used to add single or multiple elements at the end of tuples.

var hobbies:[string,boolean]=["Cricket",true];
    
hobbies.push("programming",true);

hobbies.push("bolibol",false);

hobbies.push("football",true);
console.log(hobbies);
Add tuple element in typescript
[ 'Cricket',
true,
'programming',
true,
'bolibol',
false,
'football',
true ]

Update Tuple Elements

var report:[string,number,boolean]=["Sugar",90,false];
    
console.log("Before Eating Report");

console.log(report);

report[1]=130;
report[2]=true;

console.log("After Eating Report");

console.log(report);
Update Tuple Elements
Before Eating
[ 'Sugar', 90, false ]
After Eating
[ 'Sugar', 130, true ]

Delete Tuple Operations

pop() method are used to remove existing element in tuple. this method are remove last element of tuple and return deleted element value.

var info:[number,number]=[10,20];
// Before delete tuple element
console.log("Before delete : ",info);
// Delete last element
info.pop();
// After delete tuple element
console.log("After delete : ",info);
Delete Tuple Elements
Before delete :  [ 10, 20 ]
After delete :  [ 10 ]

shift() method are use to remove first element of tuple.

var info:[string,boolean, number]=["Cricket",true,2021];
// Before delete tuple element
console.log("Before delete : ",info);
// Delete first node
info.shift();
// After delete tuple element
console.log("After delete : ",info);
Delete Tuple Elements Using Shift Method
Before delete :  [ 'Cricket', true, 2021 ]
After delete :  [ true, 2021 ]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved