Arrays & Tuples

Dynamic lists vs fixed-length pairs.

TypeScript3 min readConcept 5 of 54

Two ways to type a list

In JavaScript, an array is just a dynamic list that can hold anything. In TypeScript, we split this concept into two distinct types: Arrays and Tuples.

An **Array** (string[] or Array<string>) holds any number of elements, but they must all share the same type.

A **Tuple** ([string, number]) is an array with a fixed length and a known type at every specific index.

Why use Tuples?

Tuples are perfect for situations where the position of the data has specific meaning. The most famous example is React's useState hook, which always returns exactly two elements: a state value at index 0, and a setter function at index 1.

If useState returned a standard array like (number | Function)[], TypeScript wouldn't know which index held the number and which held the function.

Defining them

You define an array by appending [] to a type:

typescript const names: string[] = ["Alice", "Bob"]; names.push("Charlie"); // OK

You define a tuple using square brackets around a comma-separated list of types:

typescript const userRecord: [number, string] = [1, "Alice"]; // Error: Source has 3 element(s) but target allows only 2. const badRecord: [number, string] = [1, "Alice", "Admin"];

Try it

Try to push a third element into both a standard Array and a strictly-typed Tuple.

// 1. Initialize a pair
let record: (number | string)[] = [1, "Alice"];

// 2. Try to assign 3 elements
record = [1, "Alice", "Admin"];

Compile Success

An Array allows any number of elements as long as they match the allowed types (number or string).

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary difference between a standard Array and a Tuple in TypeScript?

Remember this

  • Arrays (string[]) are for dynamic-length lists of the same type.
  • Tuples ([number, string]) are for fixed-length lists where the position matters.
  • React's useState is the most common real-world example of a Tuple.
  • Use readonly to prevent accidental .push() mutations on Tuples.

Done with this concept?

Mark it complete to track your progress. No login needed.