📦 TypeScript Arrays & Tuples: Your Magical Storage Boxes!
Imagine you have different types of boxes to store your toys. Some boxes can hold many toys of the same kind, while others have special compartments for different things. That’s exactly what Arrays and Tuples are in TypeScript!
🎯 The Big Picture
Think of your toy room. You have:
- A big toy box where you keep all your cars (that’s an Array)
- A lunch box with specific spots for sandwich, fruit, and juice (that’s a Tuple)
TypeScript helps you organize your code the same way!
📚 Array Types: Your Big Toy Box
What is an Array?
An array is like a long train of boxes, where each box holds the same type of thing.
// A train of number boxes
let ages: number[] = [5, 7, 9, 12];
// A train of word boxes
let names: string[] = ["Ali", "Bob", "Cat"];
// Another way to write it
let scores: Array<number> = [100, 95, 88];
Why Does This Matter?
When you tell TypeScript “this box only holds toys,” it stops you from accidentally putting a sandwich in there!
let toys: string[] = ["car", "doll"];
toys.push("robot"); // ✅ Works!
toys.push(42); // ❌ Error! 42 isn't a toy
graph TD A[Array Box] --> B[Slot 0: car] A --> C[Slot 1: doll] A --> D[Slot 2: robot] style A fill:#4ECDC4,color:#fff style B fill:#FFE66D,color:#333 style C fill:#FFE66D,color:#333 style D fill:#FFE66D,color:#333
🔒 Readonly Arrays: The Museum Display Case
What Makes It Special?
Imagine a museum display. You can look at the dinosaur bones, but you can’t touch them! A readonly array works the same way.
const colors: readonly string[] =
["red", "blue", "green"];
// ✅ Looking is fine!
console.log(colors[0]); // "red"
// ❌ No touching allowed!
colors.push("yellow"); // Error!
colors[0] = "purple"; // Error!
Another Way to Write It
const pets: ReadonlyArray<string> =
["dog", "cat", "fish"];
// You can read...
let myPet = pets[0]; // ✅ "dog"
// But you can't change!
pets.pop(); // ❌ Error!
When Would You Use This?
When you have important data that should never change, like:
- Days of the week
- Your app’s color theme
- A list of menu items
🎁 Tuple Types: The Lunch Box with Compartments
What is a Tuple?
A tuple is like a lunch box with specific spots. The first spot is for your sandwich, the second for your fruit, the third for your juice. Each spot expects a specific thing!
// [name, age, isStudent]
let person: [string, number, boolean] =
["Emma", 10, true];
// Access like an array
console.log(person[0]); // "Emma"
console.log(person[1]); // 10
console.log(person[2]); // true
Why Not Just Use an Array?
With arrays, you can mix things up. With tuples, TypeScript makes sure everything is in its right place!
// ❌ Wrong order = Error!
let wrong: [string, number] = [42, "oops"];
// ✅ Correct order = Happy!
let right: [string, number] = ["hello", 42];
graph TD A[Tuple Lunch Box] --> B["Slot 0: string 🥪"] A --> C["Slot 1: number 🍎"] A --> D["Slot 2: boolean 🧃"] style A fill:#FF6B6B,color:#fff style B fill:#C7F464,color:#333 style C fill:#FFE66D,color:#333 style D fill:#4ECDC4,color:#333
❓ Optional Tuple Elements: Maybe There’s Dessert?
Sometimes the Last Spot is Empty
Your lunch box has a spot for dessert, but mom doesn’t always pack one. That’s an optional element!
// dessert is optional (the ?)
type Lunch = [
string, // main dish
string, // drink
string? // dessert (maybe!)
];
// Both are valid!
let lunch1: Lunch = ["pizza", "juice"];
let lunch2: Lunch = ["pizza", "juice", "cookie"];
Rules for Optional Elements
Optional elements must come at the end of the tuple, like optional toppings on ice cream!
// ✅ Optional at the end
type GoodTuple = [string, number, boolean?];
// ❌ Can't have optional in middle
type BadTuple = [string?, number, boolean];
🌊 Rest Elements: The Expandable Backpack
What if You Don’t Know How Many?
Imagine a backpack that can hold as many snacks as you want after the first two items. That’s a rest element!
// First two are fixed, then any number
type Party = [
string, // host name
number, // age
...string[] // all the guests!
];
let birthday: Party = [
"Sam",
8,
"Tom", "Amy", "Zoe", "Max"
];
Rest Can Be Anywhere!
// Rest at the start
type Scores = [...number[], string];
let game: Scores = [10, 20, 30, "Winner!"];
// Rest in the middle
type Sandwich = [
string, // bread
...string[], // fillings
string // bread
];
let sub: Sandwich = [
"wheat",
"ham", "cheese", "lettuce",
"wheat"
];
graph TD A[Rest Element Tuple] --> B[Fixed: Host Name] A --> C[Fixed: Age] A --> D["...Rest: Any # of Guests"] D --> E[Guest 1] D --> F[Guest 2] D --> G[Guest 3] D --> H[And more...] style A fill:#764ba2,color:#fff style D fill:#667eea,color:#fff
🏛️ Readonly Tuples: The Trophy Case
Protect Your Precious Data!
Just like readonly arrays, you can make tuples that nobody can change.
const winner: readonly [string, number] =
["Gold Team", 100];
// ✅ Reading is fine
console.log(winner[0]); // "Gold Team"
// ❌ No changes allowed!
winner[0] = "Silver Team"; // Error!
winner.push("extra"); // Error!
Using the “as const” Magic
There’s a cool trick to make things readonly automatically:
// "as const" makes it readonly AND precise
const point = [10, 20] as const;
// Type is: readonly [10, 20]
// Now TypeScript knows EXACTLY what's inside!
🎨 Putting It All Together
Here’s a real example combining everything:
// A game player record
type Player = readonly [
string, // player name
number, // level
boolean?, // isPremium?
...string[] // achievements
];
const hero: Player = [
"DragonSlayer",
42,
true,
"First Blood",
"Speed Run",
"Boss Defeated"
];
// Safe to read
console.log(hero[0]); // "DragonSlayer"
console.log(hero[3]); // "First Blood"
// Can't modify - it's readonly!
// hero[1] = 99; // ❌ Error!
🌟 Quick Comparison
| Feature | Array | Tuple |
|---|---|---|
| Length | Any | Fixed (usually) |
| Types | Same type | Different types OK |
| Order | Doesn’t matter | Matters a lot! |
| Use Case | List of same things | Record with fields |
🎉 You Did It!
Now you know:
- Arrays are like toy boxes for the same type of items
- Readonly arrays are display cases you can’t modify
- Tuples are lunch boxes with specific spots
- Optional elements are “maybe” spots at the end
- Rest elements let you have flexible-length sections
- Readonly tuples protect your data from changes
You’re ready to organize your TypeScript code like a pro! 🚀