Array Vs. Tuples in TypeScript


When working with TypeScript, developers have access to various data structures to store and manipulate data. Two commonly used data structures are arrays and tuples. Both arrays and tuples allow us to store multiple values, but they differ in terms of their structure and usage.

In this tutorial, we will explore the characteristics of arrays and tuples in TypeScript, discuss their differences, and provide examples to illustrate their applications.

What is an Array?

An array is a data structure that stores a collection of elements. It is an ordered list of values, where each value is identified by an index. Arrays in TypeScript can contain elements of the same type or a combination of different types. We can declare an array using square brackets, and the elements are separated by commas.

Example 1

let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: string[] = ["apple", "banana", "orange"];
let mixed: (number | string)[] = [1, "two", 3, "four"];
console.log(`The value of numbers is ${numbers}`);
console.log(`The value of fruits is ${fruits}`);
console.log(`The value of mixed is ${mixed}`);

On compiling, it will generate the following JavaScript code −

var numbers = [1, 2, 3, 4, 5];
var fruits = ["apple", "banana", "orange"];
var mixed = [1, "two", 3, "four"];
console.log("The value of numbers is ".concat(numbers));
console.log("The value of fruits is ".concat(fruits));
console.log("The value of mixed is ".concat(mixed));

Output

The above code will produce the following output −

The value of numbers is 1,2,3,4,5
The value of fruits is apple,banana,orange
The value of mixed is 1,two,3,four

Example 2

Here we try to remove the last element of the numbers array.

let numbers: number[] = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
numbers.pop(); // Removing the last element
console.log(numbers); // Output: [1, 2, 3, 4]

On compiling, it will generate the following JavaScript code −

var numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // Output: 5
numbers.pop(); // Removing the last element
console.log(numbers); // Output: [1, 2, 3, 4]

Output

The above code will produce the following output −

5
[ 1, 2, 3, 4 ]

What is a Tuple?

A tuple is a finite ordered list of elements, where each element can have a different type. Unlike arrays, tuples have a fixed length, and the types of each element are known at the time of declaration. In TypeScript, tuples are represented using square brackets, and each element is separated by a comma. We can also specify the type of each element using type annotations.

Example 3

let person: [string, number] = ["John", 25];
let point: [number, number, string] = [10, 20, "origin"];
console.log(`The value of person is ${person}`);
console.log(`The value of point is ${point}`);

On compiling, it will generate the following JavaScript code −

var person = ["John", 25];
var point = [10, 20, "origin"];
console.log("The value of person is ".concat(person));
console.log("The value of point is ".concat(point));

Output

The above code will produce the following output −

The value of person is John,25
The value of point is 10,20,origin

In the above examples, we have declared two tuples. The person tuple contains a string element followed by a number element. The point tuple contains two number elements followed by a string element.

Example 4

In this example, we try to add a boolean input true to a tuple containing string and number types and hence of type string | number. This tries to modify the data property type, resulting in an error.

let data: [string, number] = ["Hello", 42];
console.log(data.length); // Output: 2
data.push(true);
var data = ["Hello", 42];
console.log(data.length); // Output: 2
data.push(true);

Output

We get the following compile-time Output.

2

Differences Between Arrays and Tuples

Now that we understand the basic definitions of arrays and tuples in TypeScript let's explore the differences between them.

Structure

Arrays are flexible and can hold any number of elements of the same or different types. They are dynamic in nature, meaning we can add or remove elements from an array during runtime. On the other hand, tuples have a fixed length, and the types of each element are predetermined. Once a tuple is defined, we cannot add or remove elements or change their types.

Usage

Arrays are commonly used when we need to work with a collection of elements where the order or position of elements is important. We can perform operations like adding, removing, and modifying elements in an array using various array methods. Tuples, on the other hand, are typically used when we want to represent a fixed set of values with different types, such as representing coordinates or key-value pairs.

Type Safety

Arrays provide less type safety compared to tuples. In an array, we can access any element at any index, and TypeScript will allow it as long as the index is within the array bounds. This can lead to potential runtime errors if we access an element that doesn't exist or if we assume the wrong type for an element. Tuples, with their fixed length and known types, provide more type safety. TypeScript can enforce the correct usage of tuple elements, reducing the chances of runtime errors.

To summarize the differences between arrays and tuples, let's take a look at the following table −

Basis of Difference

Arrays

Tuples

Structure

Dynamic, variable length, elements of the same or different types

Fixed length, elements of different types

Usage

Collection of elements, order matters

The fixed set of values with different types

Type Safety

Less type-safe, potential runtime errors

More type-safe, enforced types

Conclusion

In conclusion, arrays and tuples are both useful data structures in TypeScript, but they have different characteristics and usages. Arrays provide flexibility in terms of length and element types, making them suitable for storing collections of elements where the order matters. Tuples, on the other hand, have a fixed length and predetermined types, making them ideal for representing a fixed set of values with different types.

It is important to choose the appropriate data structure based on the requirements of your program. Arrays are versatile and can handle a wide range of scenarios, while tuples provide stricter type safety and ensure the correct usage of fixed sets of values. By understanding the differences between arrays and tuples in TypeScript, you can make informed decisions when choosing the right data structure for your application.

Updated on: 31-Aug-2023

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements