Arrays & Tuples

TypeScript provides typed arrays to enforce consistent data element types and fixed-length tuples to represent structured data pairs.

1. Typed Arrays

There are two equivalent ways to declare typed arrays in TypeScript:

// Square bracket syntax (Preferred)
let skills: string[] = ["JavaScript", "TypeScript", "React"];

// Generic Array<T> syntax
let scores: Array<number> = [95, 88, 100];

// Array with multiple allowed types (Union Array)
let mixedData: (string | number)[] = ["Alice", 25, "Bob", 30];

2. Tuples (Fixed Length & Types)

A Tuple is a special array with a fixed number of elements, where each element has a specific known type at its exact index position.

HTTP Response Tuple Example:
// Tuple: [status_code, status_message]
let httpResponse: [number, string] = [200, "OK"];

// ❌ Error: Type 'string' is not assignable to type 'number'
// httpResponse = ["404", "Not Found"];

// Named Tuples (Improves code readability in IDEs!)
type UserCoordinate = [latitude: number, longitude: number];
let location: UserCoordinate = [37.7749, -122.4194];

3. Readonly Arrays & `as const`

Prevent accidental array mutation using ReadonlyArray<T> or as const assertions:

const colors: readonly string[] = ["red", "green", "blue"];

// ❌ Error: Property 'push' does not exist on type 'readonly string[]'
// colors.push("yellow");

const config = [404, "Not Found"] as const; // Frozen immutable tuple

Next Up

Master Enums in TypeScript: numeric enums, string enums, and const enums.

Next Lesson: Enums →