In the last chapter, you learn array in which you can store similar types of values in a single variable. But what if we want to store more than one data types values in a single array? Yes, typescript supports Tuples in which you can store more than one type of values and this is called Tuples in TypeScript.
So, in Tuples represents a heterogeneous group of values. Or we can say, tuples helps us in storing multiple fields of different types. You can also pass tuples as a parameter in any function.
var tuple_name = [val1,val2,val3,val4.. valn]
var basket= [200,"Biscit",23.50,”Jeans”];
Individual items in Tuple are called items. Since Tuples are arry, so we can access its value through its index.
1 2 3 4
var basket= [200,"Biscit",23.50, Jeans ]; console.log(basket) console.log(basket) console.log(basket)
If you look at above example, we have created a tuple, basket.This tuple
We can also declare empty Tuples and then we can fill its values.
1 2 3 4 5 6 7
var bags=  // we have declared empty Tuple bags = 'Pencil' bags = 500 bags = 'Tiffin Box' console.log(bags) console.log(bags) console.log(bags)
Since tuples is a form of array that supports different functions. Same way, Tuples also support different array functions .Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc.
1 2 3 4 5 6 7 8 9
var courses= ['Java',"C++","C","typeScript"]; console.log("Courses before push "+courses.length) // returns the tuple size console.log("Items before pop "+courses.length) console.log(courses.pop()+" popped from the tuple") console.log("Course after pop "+courses.length) courses.push('PHP') // append value to the tuple console.log("Courses after push "+courses.length) console.log("Course after pop "+courses.length)
The pop() : This function removes last item from the Tuples
The push() : This function insert new item in the Tuples
The output of the above code is as follows −
Tuples values can be changed that means you can update or change the values of tuple elements.
1 2 3 4 5
var courses= ['Java',"C++","C","typeScript"]; console.log("Tuple value at index 0 "+courses) //Update here with new value courses = ASP.NET console.log("Tuple value at index 0 changed to "+courses)
And the output will be :
You have already seen array destruct. Same like array, we can also break up Tuples into parts. And display as an individual entity.
1 2 3 4
var nums =[100,200] var [x,y] = nums console.log( x ) console.log( y )
Its output is as follows −