Course contentsShow
← TypeScript
Lesson 1370 of 1,79632. Advanced PatternsFree lesson

Tuple Types vs Array Types

Understanding fixed-length, heterogeneous tuples versus variable-length, homogeneous arrays.

What You'll Learn

You'll learn the crucial difference between fixed-length, heterogeneous tuples and variable-length, homogeneous arrays — and when each one provides better type safety.


The Fundamental Difference

In TypeScript, arrays and tuples may look similar at runtime (both are JavaScript arrays), but they represent fundamentally different type contracts:

  • Arrays are variable-length collections where every element has the same type (homogeneous)
  • Tuples are fixed-length collections where each position can have a different type (heterogeneous)

Think of an array like a bag of identical marbles — you can have any number, but they're all the same kind. A tuple is like a specific coordinate: (x, y) — exactly two values, where the first is always a number for x and the second is always a number for y.


Arrays: Homogeneous and Variable-Length

const numbers: number[] = [1, 2, 3];
numbers.push(4); // ✓ Can grow
numbers[0]; // Type: number
numbers[100]; // Type: number (might be undefined!)

const strings: string[] = ["a", "b"];
strings.push("c"); // ✓ Can grow
strings.length; // Type: number (could be any value)

Arrays don't track their length as part of the type. Every element access returns the same element type.


Tuples: Heterogeneous and Fixed-Length

const point: [number, number] = [10, 20];
// point[0] is number (x coordinate)
// point[1] is number (y coordinate)
// point[2] would be a type error

const user: [string, number] = ["Alice", 30];
// user[0] is string (name)
// user[1] is number (age)

const keyValue: [string, boolean] = ["active", true];
// keyValue[0] is string (key)
// keyValue[1] is boolean (value)

Each position in the tuple has its own specific type. The length is part of the type contract.


When Each Shines

Use tuples when:

  • You need a fixed number of elements with known positions
  • Each position has specific meaning and potentially different types
  • Return multiple related values from a function

Use arrays when:

  • The collection can grow or shrink
  • All elements represent the same kind of thing
  • You'll iterate over every element uniformly

Key Takeaway: Arrays are for collections of the same type that can change size; tuples are for fixed-length sequences where each position has specific meaning and potentially different types. Choose tuples when structure matters, arrays when flexibility matters.