Skip to content

Arrays and Maps

Introduction

Arrays, Lists, and Maps are fundamental data structures in TypeScript that allow developers to store and manage collections of data efficiently. This article provides a comprehensive understanding of how these structures are used in TypeScript, including their syntax, operations, and examples. As you know, TS is a superset of JS, so please see the article related to arrays in js.

Arrays in TypeScript

Definition and Declaration

Arrays are ordered collections of elements. In TypeScript, the type of elements that an array can contain is specified using the syntax elementType[].

let numbers: number[] = [1, 2, 3];
let names: string[] = ['Alice', 'Bob', 'Charlie'];

Accessing and Modifying Array Elements

Access elements using their index, and modify them by assigning a new value to a specific index.

let firstNumber: number = numbers[0]; // 1
numbers[1] = 5; // numbers is now [1, 5, 3]

Iteration

Use loops to iterate over array elements.

for (let num of numbers) {
  console.log(num);
}

Array Methods with Type Safety

TypeScript provides full type inference for array methods:

const numbers = [1, 2, 3, 4, 5];

// map - transforms elements
const doubled = numbers.map(n => n * 2); // number[]

// filter - keeps elements that match condition
const evenNumbers = numbers.filter(n => n % 2 === 0); // number[]

// reduce - combines elements into single value
const sum = numbers.reduce((acc, n) => acc + n, 0); // number

// find - returns first matching element or undefined
const found = numbers.find(n => n > 3); // number | undefined

Readonly Arrays

Prevent array modification using readonly:

const numbers: readonly number[] = [1, 2, 3];
// numbers.push(4); // ❌ Error: Property 'push' does not exist

// Alternative syntax
const names: ReadonlyArray<string> = ['Alice', 'Bob'];
// names[0] = 'Charlie'; // ❌ Error: Index signature only permits reading

Lists in TypeScript

In TypeScript, lists typically refer to arrays, as shown above. TypeScript does not have a separate list data structure, but arrays provide all the functionality you would expect from lists in other languages.

Maps in TypeScript

Definition and Declaration

A Map in TypeScript is a collection of key-value pairs. The Map type is part of ES6 and is available in TypeScript as well.

let map = new Map<string, number>();

Adding and Retrieving Values

Use the set method to add key-value pairs and the get method to retrieve the value associated with a key.

map.set('one', 1);
let one = map.get('one'); // 1

Iteration

Use the forEach method to iterate over the key-value pairs in the map.

map.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Working with Map Methods

// Check if key exists
if (map.has('one')) {
  console.log('Key exists');
}

// Get size
console.log(map.size); // Number of entries

// Delete an entry
map.delete('one');

// Clear all entries
map.clear();

// Iterate with for...of
for (const [key, value] of map) {
  console.log(`${key}: ${value}`);
}

// Get keys, values, or entries
const keys = Array.from(map.keys());
const values = Array.from(map.values());
const entries = Array.from(map.entries());

Record vs Map

For simple key-value pairs with string keys, you can also use Record type or object literals:

// Using Record type
const scores: Record<string, number> = {
  Alice: 95,
  Bob: 87
};

// Using Map - better for dynamic keys and non-string keys
const userScores = new Map<string, number>();
userScores.set('Alice', 95);
userScores.set('Bob', 87);

Advanced Topics

The following sections cover more advanced array and map features.

Tuple Types

Tuples allow arrays with fixed length and specific types for each position:

// Basic tuple
let person: [string, number] = ['Alice', 30];
let name = person[0];  // string
let age = person[1];   // number

// Optional elements
let coordinate: [number, number, number?] = [10, 20];

// Rest elements
let scores: [string, ...number[]] = ['Math', 95, 87, 92];

// Named tuple elements (TS 4.0+)
type Point = [x: number, y: number];
let point: Point = [10, 20];

Generic Array Functions

Create reusable functions that work with any array type:

function firstElement<T>(arr: T[]): T | undefined {
    return arr[0];
}

const num = firstElement([1, 2, 3]);      // number | undefined
const str = firstElement(['a', 'b', 'c']); // string | undefined

// With constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

const person = { name: 'Alice', age: 30 };
const name2 = getProperty(person, 'name'); // string

Array Type Guards

Handle mixed-type arrays with type guards:

type StringOrNumber = string | number;

function processItems(items: StringOrNumber[]) {
    items.forEach(item => {
        if (typeof item === 'string') {
            console.log(item.toUpperCase()); // string methods
        } else {
            console.log(item.toFixed(2));    // number methods
        }
    });
}