Arrays & Tuples
Dynamic lists vs fixed-length pairs.
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.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
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
useStateis the most common real-world example of a Tuple. - Use
readonlyto prevent accidental.push()mutations on Tuples.
Done with this concept?
Mark it complete to track your progress. No login needed.