TypeScript Tuples Tutorial
In this TypeScript tutorial we learn how to store multiple values with different types in the tuple data container.
Tuples in TypeScript are almost identical to arrays, so this lesson will be fairly easy. We cover declaring and initializing tuples, accessing and mutating their values, and adding and removing elements.
Lastly, we discuss how to destructure a tuple.
What is a tuple
A tuple is similar to an array in that it can store multiple values in a single container.
But, whereas an array can only store values of a single type, a tuple can store values of different types.
How to initialize a tuple literal
Like an array, the most straightforward way to create a tuple is by initializing a tuple literal.
To create a tuple literal, we start with a unique name, followed by the assignment operator and open and close square brackets. Inside the square brackets we add one or more values, separating them with a comma.
note It’s exactly like an array, except we don’t specify a type.
// array initialization
let name : type[] = [value1, value2, ...]
// tuple initialization
let name = [value1, value2, ...]
let user = ["John", 32]
Similar to an array, the tuple is like a table with a single row, but multiple columns.
John | Jane | Jack | Jill |
How to access tuple elements with the indexer
To access a tuple element, we use the indexer. Just like an array, each element in a tuple has a corresponding number.
0 | 1 | 2 | 3 |
---|---|---|---|
John | Jane | Jack | Jill |
These numbers form the index. When we want to access a specific element, we provide the element’s corresponding index number between open and close square brackets.
// initialization
let name = [value1, value2, ...]
// access
name[0]
let user = ["John", 32]
console.log(user[0], "is", user[1], "years old")
How to access tuple elements in a loop
TypeScript allows us to access tuple elements in a loop, providing there is some sort of counter to iterate through the elements.
let user = ["John", 32]
let i : number = 0
// while loop
while(user[i]) {
console.log(user[i])
i++
}
// for loop
for(i = 0; i < 2; i++) {
console.log(user[i])
}
We also have access to the .length property if we need to know how many elements there are in a tuple.
To use the property, we specify the tuple name, followed by a dot operator and the length keyword.
let user = ["John", 32]
console.log("There are", user.length, "elements in the 'user' tuple")
// for loop
for(var i:number = 0; i < 2; i++) {
console.log(user[i])
}
How to change tuple elements
Tuples in TypeScript are mutable, which means we can change their data at runtime.
To change the value of a tuple element, we refer to its index to access the element and then assign it a new value. We can change from one type to another.
// initialization
let name = [value1, value2, ...]
// mutation
name[0] = new_value
let user = ["John", 32]
console.log(user[0], "is", user[1], "years old")
// mutate
user[0] = "Jane"
user[1] = "28"
console.log(user[0], "is", user[1], "years old")
In the example above, we change the values of both elements. The second element used to be a number, but we changed it to a string.
How to add tuple elements
To add elements to a tuple, we use the built-in .push() method. It will push a value onto the end of the tuple.
To push an element, we write the tuple name, followed by a dot operator and push . Then, we specify the value we want to add as an argument.
name.push(value_to_add)
let user = ["John", "Doe", 32,]
// push element into the tuple
user.push("Jane")
for (let i:number = 0; i < user.length; i++) {
console.log(user[i])
}
In the example above, we push a single value into a new element at the end of the tuple.
We can push more than one element into the tuple by separating the values we want to push with a comma. The values will be added in the same order we specify.
name.push(value1, value2, ...)
let user = ["John", "Doe", 32,]
// push element into the tuple
user.push("Jane", "Doe", 28)
for (let i: number = 0; i < user.length; i++) {
console.log(user[i])
}
In the example above, we add 3 more elements to the tuple.
When we look at the list printed in the console, we can see that the elements were added in the same sequence.
John
Doe
32
Jane
Doe
28
How to remove tuple elements
TypeScript provides us with three methods to remove elements from an tuple, depending on where the element is.
- pop() - Removes an element from the end of the array.
- shift() - Removes an element from the start of the array.
- splice() - Removes an element at a specific index.
To remove an element from the end of a tuple, we use the .pop() method without any arguments.
let user = ["John", "Doe", 32,]
// remove element from
// the end of the tuple
user.pop()
for (let i:number = 0; i < user.length; i++) {
console.log(user[i])
}
The pop() method will return the value of the element which it just removed.
let user = ["John", "Doe", 32,]
// remove element from
// the end of the tuple
// and print to the page
console.log( user.pop() )
To remove an element from the start of a tuple, we use the .shift() method, without any arguments.
It works exactly the same as .pop() , except it removes the element at the start instead of the end. It will also return the value that it removed.
let user = ["John", "Doe", 32,]
// remove element from the start of
// the tuple and print to the page
console.log( user.shift() )
With the .splice() method we can remove an element, or multiple elements, at a specific index.
It requires two arguments. The first is the index where we want to start removing elements, the second is the number of elements to remove.
name.splice(index, num_elements_to_remove)
let user = ["John", "Doe", 32,]
// remove element from the start of
// the tuple and print to the page
console.log( user.splice(1, 2) )
In the example above, we remove 2 elements starting at index 1, “John”. This will remove “Doe” and 32.
The .splice() method also returns the element(s) it removed.
How to destructure a tuple
Destructuring means that we break up the structure of an entity. TypeScript supports destructuring tuples.
let user = ["John", "Doe", 32,]
// destruct the tuple into
// the separate variables
let [userFirstName, userLastName, userAge] = user
console.log( user )
console.log( userFirstName + " " + userLastName + " is " + userAge + " years old" )
In the example above, we assign the values of the tuple into separate variables.
Summary: Points to remember
- A tuple is a data container that can store multiple values of different types.
- We use [] (square brackets) to initialize a tuple with values separated by a comma.
- We do not add a type when initializing a tuple.
- To access individual elements in a tuple, we refer to its position in the tuple index.
- Tuples are mutable and element values can be changed by assigning new values to them.
- We append new elements to a tuple with the .push() method.
- We remove elements with .pop() , .shift() and .splice() .
- Tuples can be destructured.