TypeScript Arrays: A Comprehensive Tutorial

In TypeScript, arrays are used to store multiple values of the same type. TypeScript adds a level of safety to working with arrays by allowing you to specify the type of the elements in the array.

This ensures that you only store and manipulate data of the correct type, catching potential errors during development.

This tutorial will cover how to define arrays, manipulate them, and ensure type safety with practical examples. We will also explore some of the more advanced features of arrays in TypeScript, such as multi-dimensional arrays, read-only arrays, and generics.

1. Basic Array Type

In TypeScript, you can define arrays by specifying the type of the elements followed by []. This ensures that all elements in the array have the same type.

Example 1: Defining a Simple Array

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

console.log(numbers);  // Output: [1, 2, 3, 4, 5]
console.log(names);    // Output: ['Alice', 'Bob', 'Charlie']

Explanation:

numbers is declared as an array of number type, ensuring that only numbers can be added to the array.
names is declared as an array of string type, ensuring that only strings are added to the array.

2. Using the Array Generic

An alternative way to declare an array in TypeScript is to use the Array generic type.

Example 2: Using the Array Generic

let numbers: Array = [10, 20, 30, 40];
let names: Array = ['John', 'Jane', 'Jim'];

console.log(numbers);  // Output: [10, 20, 30, 40]
console.log(names);    // Output: ['John', 'Jane', 'Jim']

Explanation:

The Array syntax is equivalent to number[]. It defines an array where all elements are of type number.
Similarly, Array defines an array of strings.

3. Adding and Modifying Array Elements

You can add elements to an array using the push() method and modify elements by accessing them via their index.

Example 3: Adding and Modifying Array Elements

let fruits: string[] = ['Apple', 'Banana', 'Mango'];

// Adding elements to the array
fruits.push('Orange');
console.log(fruits);  // Output: ['Apple', 'Banana', 'Mango', 'Orange']

// Modifying an element in the array
fruits[1] = 'Blueberry';
console.log(fruits);  // Output: ['Apple', 'Blueberry', 'Mango', 'Orange']

Explanation:

The push() method adds elements to the end of the array.
Elements in the array can be accessed and modified using their index.

4. Iterating Over Arrays

You can iterate over arrays using loops like for, for…of, and forEach.

Example 4: Iterating Over Arrays

let numbers: number[] = [10, 20, 30, 40, 50];

// Using a traditional for loop
for (let i = 0; i < numbers.length; i++) { console.log(numbers[i]); } // Using for...of loop for (let num of numbers) { console.log(num); } // Using forEach method numbers.forEach(num => {
  console.log(num);
});

Explanation:

A for loop gives you full control over the iteration.
The for…of loop simplifies iteration by automatically giving you each element.
The forEach() method provides a functional way to iterate over the array.

5. Multi-Dimensional Arrays

You can create multi-dimensional arrays in TypeScript, where each element of the array is another array.

Example 5: Defining a Two-Dimensional Array

let matrix: number[][] = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[0][1]);  // Output: 2
console.log(matrix[2][2]);  // Output: 9

Explanation:

matrix is a two-dimensional array where each element is an array of numbers.
You can access elements using two indices: matrix[row][column].

6. Array Methods

TypeScript arrays inherit all the methods from JavaScript arrays. You can use methods like map(), filter(), find(), reduce(), and more.

Example 6: Using Array Methods

let numbers: number[] = [1, 2, 3, 4, 5];

// Using map to create a new array with elements doubled
let doubled = numbers.map(num => num * 2);
console.log(doubled);  // Output: [2, 4, 6, 8, 10]

// Using filter to create a new array with only even numbers
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);  // Output: [2, 4]

// Using find to get the first number greater than 3
let firstGreaterThanThree = numbers.find(num => num > 3);
console.log(firstGreaterThanThree);  // Output: 4

Explanation:

map() applies a function to each element and returns a new array.
filter() returns a new array containing only elements that satisfy a condition.
find() returns the first element that satisfies a condition, or undefined if none is found.

7. Read-Only Arrays

TypeScript provides a readonly modifier to make arrays immutable, meaning their elements cannot be changed after initialization.

Example 7: Defining a Read-Only Array

let numbers: readonly number[] = [10, 20, 30, 40];

// This will cause an error because the array is read-only
// numbers.push(50);  // Error: Property 'push' does not exist on type 'readonly number[]'.

console.log(numbers);  // Output: [10, 20, 30, 40]

Explanation:

The readonly modifier prevents the array from being modified (e.g., adding or removing elements). This is useful when you want to ensure that the array remains constant.

8. Tuples

In TypeScript, tuples are a special type of array where you can specify the types and the number of elements that the array will contain. Tuples allow arrays with mixed types.

Example 8: Defining a Tuple

let person: [string, number] = ['Alice', 25];

console.log(person[0]);  // Output: Alice
console.log(person[1]);  // Output: 25

// Adding an extra value beyond the tuple's defined length will cause an error
// person.push(true);  // Error: Argument of type 'boolean' is not assignable to parameter of type 'string | number'.

Explanation:

The tuple person is declared to have two elements: the first must be a string, and the second must be a number.
Accessing elements works the same way as with arrays, but adding elements beyond the defined length is not allowed.

9. Array with Union Types

You can define an array that contains multiple types by using union types.

Example 9: Array with Union Types

let mixedArray: (number | string)[] = [1, 'two', 3, 'four'];

console.log(mixedArray);  // Output: [1, 'two', 3, 'four']

Explanation:

mixedArray is an array that can contain both number and string types. This is useful when the array needs to hold elements of different types.

10. Generic Arrays

You can create generic functions that work with arrays of any type by using generic types.

Example 10: Generic Array Functions

function reverseArray(items: T[]): T[] {
  return items.reverse();
}

let reversedNumbers = reverseArray([1, 2, 3, 4]);
console.log(reversedNumbers);  // Output: [4, 3, 2, 1]

let reversedStrings = reverseArray(['a', 'b', 'c']);
console.log(reversedStrings);  // Output: ['c', 'b', 'a']

Explanation:

The reverseArray function is generic and works with arrays of any type (T[]). It returns the array reversed, maintaining type safety.

Conclusion

Arrays in TypeScript provide a robust way to store and manipulate collections of data with the added benefit of type safety. By specifying the type of elements in the array, TypeScript helps catch potential bugs and ensures that operations on the array are safe and predictable.

Key Topics Covered:

Basic Array Types: Defining arrays using [] or Array.
Modifying Arrays: Adding and modifying elements.
Iterating Arrays: Using loops and array methods like forEach.
Multi-Dimensional Arrays: Handling arrays with more than one dimension.
Read-Only Arrays: Using readonly to make arrays immutable.
Tuples: Defining arrays with fixed lengths and mixed types.
Union Types: Allowing arrays to contain multiple types.
Generic Arrays: Using generics to create flexible array functions.

By mastering these concepts, you can write more reliable and maintainable TypeScript code when working with arrays.

Related posts

TypeScript null & undefined: A Comprehensive Tutorial with Code Examples

TypeScript Casting: A Comprehensive Tutorial with Code Examples

TypeScript Functions: A Comprehensive Tutorial with Code Examples