Course Banner


TypeScript Tuples

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.

Syntax

var tuple_name = [val1,val2,val3,val4.. valn]

For Example

var basket= [200,"Biscit",23.50,”Jeans”];


Displaying values of Tuples

Individual items in Tuple  are called items. Since Tuples are arry, so we can access its value through its index.

Example: Simple Tuple

1
2
3
4
var basket= [200,"Biscit",23.50,Jeans];
console.log(basket[0]) 
console.log(basket[1])
console.log(basket[2])

If you look at above example, we have created  a tuple, basket.This  tuple

Declaring Empty Tuple

We can also declare empty Tuples and then we can fill its values.

Example :

1
2
3
4
5
6
7
var bags= [] // we have declared empty Tuple
bags[0] = 'Pencil'
bags[1] =  500
bags[2] =  'Tiffin Box'
console.log(bags[0])
console.log(bags[1])
console.log(bags[2])

Tuple Functions

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.

Example

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 −


Editing Tuples

Tuples values can be changed that means you can update or change the values of tuple elements.

Example

1
2
3
4
5
var courses= ['Java',"C++","C","typeScript"];
console.log("Tuple value at index 0 "+courses[0]) 
//Update here with new value 
courses[0] = ASP.NET     
console.log("Tuple value at index 0 changed to   "+courses[0])

And the output will be :


Destructuring a Tuple

You have already seen array  destruct. Same like array, we can also break up Tuples into parts. And display as an individual entity.

Example

1
2
3
4
var nums =[100,200]
var [x,y] = nums
console.log( x )
console.log( y )

Its output is as follows −


Ad Image