TypeScript Tuples for Beginners
Learn what TypeScript tuples are and how to use them to write more efficient and reliable code.
Welcome! In this article, we will cover the fundamentals of tuples in TypeScript and we will also see how they are different from arrays.
Introduction to Tuples
Let's start by talking a little bit about the concept of a tuple.
Concept
Tuples are built-in data structures in TypeScript. They are very similar to arrays with two key differences.
They have:
A fixed length.
A specific data type for each element.
Since tuples have a fixed length, you cannot add or remove elements from a tuple after you define it.
The elements of a tuple must also match the specific data types that you define in your type annotation.
When to Use Tuples
Now that you know what tuples are, let's see when you should use them and when you should use arrays:
Use them when... you need to store a specific sequence of related values. If you are completely sure that the sequence will not change in the future, you should define a tuple.
Avoid them when... you anticipate that the sequence may have to be extended, shortened, or modified in a way that may change the data types of the elements. In that case, it is recommended to use an array instead.
Advantages of TypeScript Tuples
Why should you use tuples? Let's see:
They use all the power of static typing because they enforce specific data types for specific values in a specific order. This can help you to detect and fix bugs early in the development process.
They can make your code easier to read and understand because you will be able to easily determine the data type of each element in the sequence.
Tuples Syntax and Operations
Great. Now that you know what TypeScript tuples are, let's see how you can define and work with tuples in your TypeScript programs.
How to Define a Tuple
To define a tuple in TypeScript, you should follow this syntax:
let tupleName: [type1, type2, type3] = [value1, value2, value3];
The
let
keyword because we usually variable to store the tuple.The name of the variable.
The type annotation within the square brackets. For tuples, we need to specify the data type of each one of the elements that will be stored in the tuple. We could say that we write one data type per "index".
The assignment operator
=
.The tuple with the actual elements/values.
A semicolon
;
.
For example, here we have an example of a tuple with three elements of the data type number
:
let hexColor: [number, number, number] = [66, 135, 245];
Notice how each type annotation corresponds to the element at its corresponding position.
Here we have another example but this time we have different data types:
let student: [string, string, number] = ["Gino", "Smith", 78];
In this tuple:
string
corresponds to index 0,"Gino"
.string
corresponds to index 1,"Smith"
.number
corresponds to index 2,78
.
Fixed Length
Having a fixed length is one of the key features of tuples in TypeScript.
If you write three data types in the type annotation, the tuple must have three values of these data types in the same order as they were defined.
But if you write a shorter or longer tuple, you will see an error. ๐ฑ
In this example, we write three data types in the type annotation but only two values in the tuple:
let student: [string, string, number] = ["Gino", "Smith"];
If we hover over the name of the variable, we will see this error warning us that the type of the value is "not assignable" to a variable with the type specified in the type annotation:
Custom Types in Tuples
You can also define and assign custom data types for your tuples.
For example, you can define a custom type to use it in your tuple and throughout your program. This way, you can avoid repetition and you just need to write the name of the custom type in the type annotation:
type Student = [string, string, number];
let student: Student = ["Gino", "Smith", 78];
If the values do not match the data types, you will see this type of error:
Type '<type>' is not assignable to type '<type>'.
This is an example of a data type mismatch. The values are in a different order. Instead of having a string followed by a number, we have a number followed by a string.
This mismatch results in an error that you can see if you hover over the value with the red squiggly line:
This is super helpful for detecting any potential errors and bugs even before compiling and running our program.
Accessing Tuple Elements
Now that you know how to define tuples in TypeScript, let's see how you can perform common operations.
To access tuple elements, we use their corresponding indices just like we would with arrays:
let pizzaOrder: [string, number] = ["Margherita", 9.67];
console.log(pizzaOrder[0]);
console.log(pizzaOrder[1]);
This is the output:
Margherita
9.67
Modifying Tuple Elements
In TypeScript, tuples have a fixed length, but they are not immutable and that is great because their values can be updated.
The only requirement is that the data type of the new value must match the corresponding type annotation.
In this example, we replace the value 9.67
by the value 10.2
. In the context of this example, this number represents the price of the pizza order (yummy, right? ๐๐).
let pizzaOrder: [string, number] = ["Margherita", 9.67];
// Modify the second element of the tuple.
pizzaOrder[1] = 10.2;
console.log(pizzaOrder);
This is the general syntax for modifying a value in a tuple:
tuple[index] = newValue;
Working with TypeScript Tuples
Tuple Methods
You can work with tuples in your code the same way that you worked with arrays in JavaScript.
The only difference is that you will not be able to call any methods that change the length of the tuple. These methods, such as .append()
, .pop()
, and such, will not be defined.
For example, if you try to append an element to a tuple, you will see an error warning you that this method is not defined:
let animals: [string, string, string] = ["Lion", "Tiger", "Elephant"];
animals.append();
This will throw an error similar to
"Property 'append' does not exist on type <tuple_type>"
But if you call another method that does not try to modify the length of the tuple, you will be able to compile and run the code successfully:
let animals: [string, string, string] = ["Lion", "Tiger", "Elephant"];
animals.slice(1);
This line of code will run successfully.
Iterating over Tuples
You can also iterate over tuples using for loops just like you can iterate over arrays. The only difference is that you will always iterate over the same number of elements because they have a fixed length.
For example:
let animals: [string, string, string] = ["Lion", "Tiger", "Elephant"];
for (let i = 0; i < animals.length; i++) {
console.log(animals);
}
You can also use other types of loops, such as the for..in
loop:
let animals: [string, string, string] = ["Lion", "Tiger", "Elephant"];
for (let animal in animals) {
console.log(animal);
}
Tuple Destructuring in TypeScript
Destructuring is another helpful operation that you can perform on tuples to assign their values to individual variables.
This is the general destructuring syntax applied to a tuple with three elements:
let [variable1, variable2, variable3] = tuple;
This works exactly the same as array destructuring in JavaScript. You write one variable per value in the tuple and the values will be assigned to their corresponding variable from left to right:
let animals: [string, string, string] = ["Lion", "Tiger", "Elephant"];
let [lion, tiger, elephant] = animals;
console.log(lion); // Lion
console.log(tiger); // Tiger
console.log(elephant); // Elephant
Conclusion
TypeScript tuples are built-in data structures with a fixed length and a specific sequence of data types for each position in the tuple.
You cannot add or remove elements from a tuple in TypeScript but you can call methods that do not modify the length of the tuple.
You can use both built-in and custom data types in tuple type annotations.
If the data types of the values and the type annotations do not match, you will see an error. This will help you to prevent errors and catch potential bugs early in the development process.
Thank you for reading my article! Now you know more about how to work with tuples in TypeScript. To learn more about TypeScript, check out my series below.
If you would like to find more coding tutorials, follow me on YouTube (Coding with Estefania) and X (@EstefaniaCassN). Have an awesome day. ๐