Collections in TypeScript - Arrays and Maps


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.


// 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.


// Adding elements to an array
// Removing elements from an array
// Iterating through an array
for (const number of numbers) {
// 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.


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

Iterating Maps

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


for (const key of personMap.keys()) {
for (const value of personMap.values()) {


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.