← Back to Course

🎯 Arrays & Tuples

Arrays and tuples are essential for storing collections of data. TypeScript provides strong typing for arrays, ensuring all elements match expected types. This topic is demonstrated extensively in the TypeLand Adventure Game!

Array Types

TypeScript offers two syntaxes for array types. Both are equivalent:

Example: Array Type Syntax

// Syntax 1: Type followed by []
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
let flags: boolean[] = [true, false, true];

// Syntax 2: Array<Type> (generic syntax)
let scores: Array<number> = [100, 95, 87];
let colors: Array<string> = ["red", "green", "blue"];

// Both syntaxes work the same way
numbers.push(6);        // ✓ OK
// numbers.push("7");   // ✗ Error: Argument of type 'string' is not assignable

Array Methods with Types

TypeScript understands array methods and maintains type safety throughout:

Example: Type-Safe Array Methods

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

// map - transforms each element
const doubled: number[] = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// filter - keeps elements matching condition
const evens: number[] = numbers.filter(n => n % 2 === 0);
// [2, 4]

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

// reduce - reduces array to single value
const sum: number = numbers.reduce((total, n) => total + n, 0);
// 15

// forEach - iterate with side effects
numbers.forEach(n => console.log(n));

// some - test if at least one element matches
const hasLarge: boolean = numbers.some(n => n > 4);
// true

Tuples

Tuples are fixed-length arrays where each position has a specific type. Perfect for coordinates, key-value pairs, and structured data!

Example: Tuple Types

// Tuple type: [type1, type2, ...]
type Coordinate = [number, number];

// TypeLand Adventure Game uses coordinates!
const playerPosition: Coordinate = [5, 10];  // [row, column]
const treasureLocation: Coordinate = [8, 3];

// Access tuple elements by index
const row: number = playerPosition[0];     // 5
const col: number = playerPosition[1];     // 10

// Tuple with mixed types
type User = [string, number, boolean];
const newUser: User = ["Alice", 25, true];
const [username, age, isActive] = newUser;  // Array destructuring

// Named tuple elements (TypeScript 4.0+)
type Point3D = [x: number, y: number, z: number];
const point: Point3D = [10, 20, 30];

Real Example from TypeLand

Here's how arrays and tuples are used in the TypeLand Adventure Game:

Example: Game Code (Simplified)

// Coordinate tuple type
type Coordinate = [number, number];

// Collectible entry: position + item type
type CollectibleEntry = [Coordinate, string];

// Array of collectibles on the map
const collectibles: CollectibleEntry[] = [
  [[2, 3], "TREASURE_CHEST"],
  [[5, 8], "MAGIC_ORB"],
  [[10, 12], "ANCIENT_SCROLL"]
];

// Hero's backpack (array of collected items)
class Hero {
  private backpack: string[] = [];
  
  collectItem(item: string): void {
    this.backpack.push(item);
  }
  
  getItemCount(itemType: string): number {
    return this.backpack.filter(item => item === itemType).length;
  }
}

// Check if position has a collectible
function findCollectible(pos: Coordinate): CollectibleEntry | undefined {
  return collectibles.find(([coord, _]) => 
    coord[0] === pos[0] && coord[1] === pos[1]
  );
}

Multi-Dimensional Arrays

Arrays can contain other arrays, creating 2D grids perfect for game maps:

Example: 2D Arrays

// 2D array type
type Grid = number[][];

// Creating a 3x3 game board
const gameBoard: Grid = [
  [0, 1, 0],
  [1, 0, 1],
  [0, 1, 0]
];

// Access elements: board[row][column]
const centerCell = gameBoard[1][1];  // 0

// TypeLand uses 2D arrays for terrain
type TerrainGrid = string[][];
const terrain: TerrainGrid = [
  ["MEADOW", "MEADOW", "LAKE"],
  ["SAND", "STONE", "LAKE"],
  ["MEADOW", "SAND", "SAND"]
];

🎯 Key Concepts

  • Arrays hold multiple values of the same type
  • Use type[] or Array<type> syntax
  • Tuples have fixed length and can have different types per position
  • Tuples are great for coordinates: [x, y]
  • Array methods like map, filter, find maintain type safety
  • 2D arrays are arrays of arrays: type[][]
  • The TypeLand game uses both extensively for map data and collectibles!
← Back to Beginner Course