Collections in TypeScript - Arrays and Maps


Introduction

Collections are essential data structures in TypeScript and many other programming languages. They are used to store and manipulate sets of data. In this guide, we'll explore two common types of collections in TypeScript: arrays and maps. We'll learn how to create, manipulate, and work with them effectively.


Arrays in TypeScript

An array is an ordered list of values that can be of the same or different types. In TypeScript, you can create arrays using square brackets [] or the Array generic type.


Example:

// Creating an array using square brackets
const numbers: number[] = [1, 2, 3, 4, 5];
// Creating an array using Array generic type
const fruits: Array<string> = ["apple", "banana", "cherry"];

Common Array Operations

Arrays in TypeScript provide a range of operations, including adding and removing elements, iterating through elements, and searching for values.


Example:

// Adding elements to an array
numbers.push(6);
numbers.unshift(0);
// Removing elements from an array
fruits.pop();
fruits.shift();
// Iterating through an array
for (const number of numbers) {
console.log(number);
}
// Searching for a value in an array
const index = fruits.indexOf("banana");

Maps in TypeScript

A map is a collection of key-value pairs. In TypeScript, you can use the Map built-in class to create maps.


Example:

const personMap = new Map<string, string>();
personMap.set("name", "Alice");
personMap.set("age", "30");
const name = personMap.get("name");
const hasEmail = personMap.has("email");
personMap.delete("age");

Iterating Maps

You can iterate through the keys and values of a map using the keys() and values() methods or the for...of loop.


Example:

for (const key of personMap.keys()) {
console.log(key);
}
for (const value of personMap.values()) {
console.log(value);
}

Conclusion

Arrays and maps are essential collection types in TypeScript that help you manage and manipulate data efficiently. Understanding how to create, modify, and work with these data structures is crucial for building robust and versatile applications. Whether you need to store a list of items or maintain key-value associations, arrays and maps are valuable tools in your TypeScript development toolbox.