6. Array & Tuples

Arrays and tuples are essential data structures in TypeScript, allowing developers to work with collections of values. In this article, we’ll explore how to create arrays, specify array types, and introduce the concept of tuples.

Creating Arrays

In TypeScript, you can create arrays using square brackets [] or the Array constructor. You can also initialize arrays with values at the time of declaration.

Using Square Brackets

// Creating an array of numbers using square brackets
const numbers: number[] = [1, 2, 3, 4, 5];

// Creating an array of strings using square brackets
const fruits: string[] = ["apple", "banana", "cherry"];

Using the Array Constructor

// Creating an array of numbers using the Array constructor
const numbers: Array<number> = new Array(1, 2, 3, 4, 5);

// Creating an array of strings using the Array constructor
const fruits: Array<string> = new Array("apple", "banana", "cherry");

Initializing Arrays

You can also initialize arrays with a fixed size and fill them with values using the fill method:

// Initialize an array with a fixed size and fill it with zeros
const zeros: number[] = new Array(5).fill(0);

// Initialize an array with a fixed size and fill it with a specific value
const ones: number[] = new Array(3).fill(1);

Array Types

TypeScript allows you to specify the type of elements within an array using square brackets notation Type[] or the generic Array<Type>. This helps catch type-related errors at compile-time.

const numbers: number[] = [1, 2, 3, 4, 5];
const fruits: string[] = ["apple", "banana", "cherry"];

TypeScript infers the array type based on the elements you provide. In the examples above, numbers is of type number[], and fruits is of type string[].

Array Methods

TypeScript provides built-in methods and properties for arrays, such as push, pop, length, forEach, and many more. These methods help you manipulate and work with arrays efficiently.

Tuples

Tuples are a special type of array in TypeScript that allow you to express an array where the type of a fixed number of elements is known, but their order may not matter. Tuples are defined using square brackets and type annotations for each element.

// Declare a tuple with two elements of specific types
const employee: [string, number] = ["John Doe", 30];

// Accessing tuple elements by index
const name: string = employee[0]; // "John Doe"
const age: number = employee[1]; // 30

Tuples are particularly useful when working with functions that return multiple values with different types or when representing structured data with a known format.

Array Destructuring

Array destructuring is a convenient way to extract values from arrays and assign them to variables. It allows you to destructure arrays into individual elements, making it easier to work with the data.

const numbers: number[] = [1, 2, 3];

// Destructuring the array into individual variables
const [first, second, third] = numbers;

console.log(first);  // 1
console.log(second); // 2
console.log(third);  // 3

Array destructuring is particularly useful when working with functions that return arrays or when extracting values from complex data structures.

Working with Tuples

Tuples in TypeScript are fixed-length arrays that can hold values of different types. You can access tuple elements by index and leverage type annotations for type safety.

// Defining a tuple type
const employee: [string, number] = ["John Doe", 30];

// Accessing tuple elements
const name: string = employee[0]; // "John Doe"
const age: number = employee[1];  // 30

Tuples are especially handy when you need to represent structured data with a known format, such as a pair of values or the components of a date.

Rest Parameters

Rest parameters allow you to capture a variable number of function arguments as an array. They are denoted by three dots (...) followed by a parameter name and must appear as the last parameter in a function’s parameter list.

function sum(...numbers: number[]): number {
    return numbers.reduce((total, num) => total + num, 0);
}

const result1: number = sum(1, 2, 3, 4, 5); // 15
const result2: number = sum(10, 20);         // 30

In this example, the sum function accepts any number of arguments and calculates their sum. The rest parameter numbers captures all passed arguments into an array.

Rest parameters are useful when you want to create flexible functions that can handle varying numbers of arguments.

Conclusion

Arrays and tuples are fundamental data structures in TypeScript that allow you to work with collections of values. By specifying array types and using tuples, you can make your code more type-safe and structured, reducing the likelihood of runtime errors and improving code clarity. Understanding how to create, manipulate, and type arrays and tuples is essential for effective TypeScript development.

Array destructuring, working with tuples, and using rest parameters are valuable techniques that enhance your ability to work with complex data and create more versatile functions in TypeScript. Understanding how to destructure arrays, work with tuples, and capture variable arguments using rest parameters will make your TypeScript code more efficient, readable, and maintainable.

Previous
Next