Skip to content
beginner Phase 1 · TypeScript Fundamentals

Arrays & Tuples

Work with typed arrays, tuples, and readonly collections.

45m
0 problems
Topic Progress 0%

Typed Arrays

Typed Arrays

TypeScript arrays can be typed using two syntaxes.

Array Syntax

// Using Array<T> generic
let numbers: Array<number> = [1, 2, 3];
let names: Array<string> = ['Alice', 'Bob'];

// Using shorthand [] syntax (more common)
let scores: number[] = [95, 87, 92];
let flags: boolean[] = [true, false, true];

// Array of objects
let users: { name: string; age: number }[] = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];

// Using interface for cleaner syntax
interface User {
  name: string;
  age: number;
}
let typedUsers: User[] = [
  { name: 'Alice', age: 30 }
];

Multidimensional Arrays

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

// Accessing elements
const value: number = matrix[1][2]; // 6

// Array of arrays with different types
let mixed: (string | number)[][] = [
  [1, 'hello'],
  [2, 'world']
];

Tuples

Tuples

Tuples are fixed-length arrays where each element has a specific type.

Basic Tuples

// A tuple: first element is string, second is number
let person: [string, number] = ['Alice', 30];

// person = [30, 'Alice']; // Error: wrong order
// person = ['Alice'];     // Error: missing element
// person = ['Alice', 30, true]; // Error: too many elements

// Accessing tuple elements
const name: string = person[0]; // 'Alice'
const age: number = person[1];  // 30

// Destructuring
const [n, a] = person;

Named Tuples (Documentation Only)

// Named elements for clarity (erased at runtime)
type HttpResponse = [status: number, body: string, timestamp: Date];

const response: HttpResponse = [200, 'hello', new Date()];

Optional Tuple Elements

// Optional third element
type Config = [string, number, boolean?];

const a: Config = ['db', 5432];       // OK
const b: Config = ['db', 5432, true]; // OK

Rest Elements in Tuples

// Variable length tuples
type StringNumberBooleans = [string, number, ...boolean[]];

const a: StringNumberBooleans = ['hello', 1];
const b: StringNumberBooleans = ['hello', 1, true, false, true];

// Common use case: rest parameters
type Rest = [string, ...number[]];

Readonly Arrays

Readonly Arrays

Readonly arrays prevent mutation of elements.

readonly Modifier

let colors: readonly string[] = ['red', 'green', 'blue'];

// colors.push('yellow');    // Error
// colors[0] = 'purple';     // Error
// colors.length = 0;         // Error

// You can still read
const first = colors[0];     // 'red'
const len = colors.length;   // 3

ReadonlyArray Generic

let numbers: ReadonlyArray<number> = [1, 2, 3];

// Same restrictions as readonly
// numbers.push(4); // Error

Tuple Mutability

// Regular tuple - elements can be reassigned
let mutable: [string, number] = ['hello', 42];
mutable[0] = 'world'; // OK

// Readonly tuple
let immutable: readonly [string, number] = ['hello', 42];
// immutable[0] = 'world'; // Error

Converting Between Mutable and Readonly

// Mutable to readonly
const mutableArr = [1, 2, 3];
const readonlyArr: readonly number[] = mutableArr;

// Readonly to mutable (creates a copy)
const arr = [...readonlyArr]; // mutable copy
arr.push(4); // OK on the copy

const Assertions for Tuples

// as const creates deeply readonly tuples
const point = [10, 20] as const;
// type: readonly [10, 20]
// point[0] = 5; // Error

Array Methods with Types

Array Methods with Types

map, filter, reduce

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

// map returns same type array
const doubled: number[] = numbers.map(n => n * 2);

// filter narrows the type
const evens: number[] = numbers.filter(n => n % 2 === 0);

// reduce needs explicit accumulator type
const sum: number = numbers.reduce((acc, n) => acc + n, 0);

// Type predicate for filtering
type Cat = { type: 'cat'; name: string };
type Dog = { type: 'dog'; name: string };
type Pet = Cat | Dog;

const pets: Pet[] = [
  { type: 'cat', name: 'Whiskers' },
  { type: 'dog', name: 'Rex' }
];

const cats: Cat[] = pets.filter((pet): pet is Cat => pet.type === 'cat');

find and Type Guarding

interface User {
  id: number;
  name: string;
  email?: string;
}

const users: User[] = [
  { id: 1, name: 'Alice', email: 'alice@test.com' },
  { id: 2, name: 'Bob' }
];

// find returns T | undefined
const user = users.find(u => u.id === 1);
if (user) {
  console.log(user.name); // safe
}

// Non-null assertion (use sparingly)
const user2 = users.find(u => u.id === 1)!;
console.log(user2.name); // assumes user exists

spread and destructuring

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

const [first, ...rest] = merged;
// first: number, rest: number[]