TypeScript Tuple: A Complete Guide to Understand Tuples in TS

What is a tuple in TypeScript?

A tuple in TypeScript is a special type of array where each element in the tuple can be of a different type.

Tuples can hold data of one or more types, such as a combination of numbers and strings, and so on.

In simple words, a tuple is like a box where you can put different kinds of things, not just the same type.

As we have learned in our previous discussions, arrays are typically used to store multiple values of the same type, there are instances when we need to hold a collection of different types of values in a single variable. In such cases, we opt for Tuples.

Syntax:

let tuple_name = [val1, val2, val3, ...val n];  

Here’s an example of a tuple in TypeScript:

let sampleTuple: [number, boolean, string]; // define our tuple
sampleTuple = [8, true, 'Hi, welcome to Itsourcecode']; // initialize correctly
console.log(sampleTuple);

Output:

[ 8, true, 'Hi, welcome to Itsourcecode' ]

Moreover, it’s also possible to define an empty tuple and decide to assign values to it at a later stage.

For example:

let sampletuple = []; 
sampletuple[0] = 100
sampletuple[1] = 200

Accessing values in Tuples

In a tuple, each value is called an item. You can find an item by its position, or index, in the tuple.

The first item is at position zero, and the last item is at position n-1, where n is the total number of items in the tuple.

Syntax:

tuple_name[index]

Example:


let sampletuple = [8,"Hi, welcome to Itsourcecode"]; 
console.log(sampletuple[0]) 
console.log(sampletuple[1])

You can test the above example here! ➡TyspeScript Online Compiler

Output:

8
Hi, welcome to Itsourcecode

For our next example, we have an empty tuple:

let sampletuple = [] 
sampletuple [0] = 100
sampletuple [1] = 200

console.log(sampletuple [0]) 
console.log(sampletuple [1])

Output

100
200

Tuple Operations

Tuples in TypeScript have a variety of operations such as adding a new item or removing an existing item, among others.

A tuple has two (2) operations:

  1. Push()

The push() operation is used to add an element to the tuple.

let student: [number, string] = [80, "Programming"];
student.push(90, "Software Development"); 
console.log(student); 

You can test the above example here! ➡TyspeScript Online Compiler

Output:

[ 80, 'Programming', 90, 'Software Development' ]

  1. Pop()

The pop() operation is used to remove the last element from a tuple in TypeScript.

This operation modifies the original tuple and returns the removed element.

Example:

let sampleTuple: [number, string, boolean] = [8, 'Hi, welcome to itsourcecode', true]; // define and initialize our tuple

console.log(sampleTuple); // Output: [ 8, 'Hi, welcome to itsourcecode', true ]

let poppedItem = sampleTuple.pop(); // pop operation

console.log(poppedItem); // Output: true
console.log(sampleTuple); // Output: [ 8, 'Hi, welcome to itsourcecode' ]

You can test the above example here! ➡TyspeScript Online Compiler

Output:

[ 8, 'Hi, welcome to itsourcecode', true ]
true
[ 8, 'Hi, welcome to itsourcecode' ]

Named Tuples

Named tuples are used to give a name to each part of the array.

Example:

type Point = [x: number, y: number]; // Named tuple type

let pointA: Point = [5, 10]; // Initializing a named tuple

In our example above, Point is a named tuple type where “x” represents the first number (the x-coordinate) and “y” represents the second number (the y-coordinate).

When we initialize pointA, we need to provide two numbers in the order of [x, y].

Updating or Modify Tuples

Tuples are changeable it simply means you can modify or alter the values of elements within a tuple.

To change the values of a tuple, we use the index of the elements and the assignment operator.

Here’s an example to illustrate this:

let sampleTuple: [number, string, boolean] = [8, 'Hi, Welcome to Itsourcecode', true]; // define and initialize our tuple

console.log(sampleTuple); // Output: [ 8, 'Hi, Welcome to Itsourcecode', true ]

// Update the first element
sampleTuple[0] = 100;
console.log(sampleTuple); // Output: [ 100, 'Hi, Welcome to Itsourcecode', true ]

// Update the second element
sampleTuple[1] = 'SourceCode';
console.log(sampleTuple); // Output: [ 100, 'SourceCode', true ]

// Update the third element
sampleTuple[2] = false;
console.log(sampleTuple); // Output: [ 100, 'SourceCode', false ]

As you can see in our given example above, first I define and initialize a tuple “sampleTuple”.

Then update each element of the tuple using their respective indices (0 for the first element, 1 for the second, and 2 for the third).

After I update each element, I log the tuple to the console to see the updated values.

You can test the above example here! ➡TyspeScript Online Compiler

Output:

[ 8, 'Hi, Welcome to Itsourcecode', true ]
[ 100, 'Hi, Welcome to Itsourcecode', true ]
[ 100, 'SourceCode', true ]
[ 100, 'SourceCode', false ]

Please take note that though tuples in TypeScript are mutable, they still maintain their type safety.

This means you can’t assign a value of a wrong type to a tuple element.

For example, trying to assign a string to the first element of “sampleTuple” (which is of type number) would result in a TypeScript error.

Destructuring a Tuple

Destructuring is the process of unpacking the elements of a structure.

This feature is fully supported because tuples are just like arrays, we can break them down too.

Destructuring is a convenient way to extract multiple values from data stored in (possibly nested) objects and arrays.
It can be used with any iterable, not just arrays, and it allows you to unpack values from complex data structures into distinct variables.

Example:

let sampleTuple: [number, string, boolean] = [8, 'Hi, Welcome to Itsourcecode', true]; // define and initialize our tuple

console.log(sampleTuple); // Output: [ 8, 'Hi, Welcome to Itsourcecode', true ]

// Destructure the tuple
let [sampleNumber, sampleString, sampleBoolean] = sampleTuple;

console.log(sampleNumber); // Output: 8
console.log(sampleString); // Output: 'Hi, Welcome to Itsourcecode'
console.log(sampleBoolean); // Output: true

In our example, first I define and initialize a tuple “sampleTuple”.

Then I destructure sampleTuple into three new variables: sampleNumber, sampleString, and sampleBoolean.

These new variables hold the values of the corresponding elements in the tuple.

You can test the above example here! ➡TyspeScript Online Compiler

Output:

[ 8, 'Hi, Welcome to Itsourcecode', true ]
8
Hi, Welcome to Itsourcecode
true

What is the difference between an array and a tuple in TypeScript?

Both arrays and tuples in TypeScript are used to store multiple values, but they are used in slightly different ways:

ArrayTuple
An array in TypeScript is a collection that can hold multiple items, but all of these items must be of the same type. A tuple in TypeScript is a special kind of array with a fixed number of items, and each item has a specific type.
let subjects: string[] = [‘Programming’, ‘SoftEng’, ‘Web Dev’];let subjectAndGrade: [string, number] = [‘Programming’, 95];

Conclusion

Finally, we are done discussing the tuple in TypeScript, which is a special type of array where each element in the tuple can be of a different type.

Tuples can hold data of one or more types, such as a combination of numbers and strings, and so on.

I hope that this article helps you to have a clearer or better understanding when it comes to tuples.

And now you can explore your coding after learning about TypeScript tuples.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment