TypeScript Arrays

Welcome to another tutorial by The Coding College! At The Coding College, our goal is to make coding concepts straightforward and actionable for all developers. Today, we’ll dive into TypeScript Arrays, a fundamental data structure for organizing and manipulating collections of data.

What is an Array in TypeScript?

An array in TypeScript is a collection of elements of the same type, stored in a single variable. Arrays help organize data for easy access, manipulation, and iteration.

Declaring Arrays in TypeScript

Syntax for Declaring an Array

There are two ways to define an array in TypeScript:

  • Using Square Brackets ([])
let numbers: number[] = [1, 2, 3];
  • Using the Array Generic
let fruits: Array<string> = ["apple", "banana", "cherry"];

Examples of Arrays

Number Array

let scores: number[] = [95, 80, 85];
console.log(scores); // Output: [95, 80, 85]

String Array

let colors: string[] = ["red", "green", "blue"];
console.log(colors); // Output: ["red", "green", "blue"]

Boolean Array

let switches: boolean[] = [true, false, true];
console.log(switches); // Output: [true, false, true]

Mixed Type Array (with Union Types)

let mixed: (string | number)[] = [1, "hello", 3];
console.log(mixed); // Output: [1, "hello", 3]

Working with Arrays

1. Accessing Array Elements

Use the index to access elements (indices start at 0):

let fruits: string[] = ["apple", "banana", "cherry"];
console.log(fruits[1]); // Output: banana

2. Adding and Removing Elements

  • Push: Add elements to the end of the array.
  • Pop: Remove the last element.
let numbers: number[] = [1, 2, 3];
numbers.push(4); // [1, 2, 3, 4]
numbers.pop();   // [1, 2, 3]

3. Iterating Over an Array

Use a loop to iterate through elements:

let languages: string[] = ["TypeScript", "JavaScript", "Python"];
for (let lang of languages) {
    console.log(lang);
}
// Output: 
// TypeScript
// JavaScript
// Python

Advanced Array Features

1. Tuples

Tuples are a special kind of array where the types and number of elements are fixed.

let user: [string, number] = ["John", 25];
console.log(user[0]); // Output: John
console.log(user[1]); // Output: 25

2. Multi-Dimensional Arrays

Arrays can contain other arrays, allowing you to represent matrices or tables.

let matrix: number[][] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
console.log(matrix[1][2]); // Output: 6

3. Array Methods

TypeScript supports all common JavaScript array methods:

MethodDescriptionExample
concat()Merges two or more arrays.arr1.concat(arr2)
slice()Returns a portion of an array.arr.slice(1, 3)
map()Applies a function to each element.arr.map(x => x * 2)
filter()Returns elements that match a condition.arr.filter(x => x > 10)
reduce()Reduces the array to a single value.arr.reduce((a, b) => a + b)

Common Errors and Tips

1. Type Mismatch

Assigning elements of the wrong type will result in a compile-time error.

let numbers: number[] = [1, 2, "three"]; // Error: Type 'string' is not assignable to type 'number'.

2. Out of Bounds Access

Accessing an index outside the array bounds returns undefined.

let arr: number[] = [1, 2, 3];
console.log(arr[10]); // Output: undefined

3. Immutable Tuples

When using tuples, ensure you don’t add extra elements:

let tuple: [string, number] = ["hello", 10];
// tuple.push(20); // Error: Property 'push' does not exist on type '[string, number]'

Real-World Use Cases for TypeScript Arrays

1. Data Storage

Arrays are perfect for storing lists like user IDs, product names, or API responses.

let userIds: number[] = [101, 102, 103];

2. Data Transformation

Use array methods to process and filter data:

let prices: number[] = [100, 200, 300];
let discountedPrices = prices.map(price => price * 0.9);
console.log(discountedPrices); // Output: [90, 180, 270]

3. Building Tables or Grids

Multi-dimensional arrays can represent tabular data or grid layouts.

let grid: string[][] = [
    ["X", "O", "X"],
    ["O", "X", "O"],
    ["X", "X", "O"],
];

Conclusion

Arrays are a foundational data structure in TypeScript, offering flexibility and powerful features for handling collections of data. By mastering arrays, you can build more robust and scalable applications.

Leave a Comment