Episode 20 of 21
Tuples
Fixed-length arrays with specific types at each position — TypeScript tuples explained.
Tuples
Tuples are fixed-length arrays where each element has a specific type at a specific position.
Basic Tuple
let tup: [string, number, boolean] = ["Mario", 25, true];
tup[0] = "Luigi"; // ✅ string at position 0
tup[0] = 30; // ❌ Error — must be string at position 0
tup[1] = "hello"; // ❌ Error — must be number at position 1
Tuples vs Arrays
| Feature | Array | Tuple |
|---|---|---|
| Length | Variable | Fixed |
| Types | Same type (or union) | Specific type per position |
| Order | Any order | Fixed order |
Named Tuples (TS 4.0+)
type User = [name: string, age: number, active: boolean];
const user: User = ["Mario", 30, true];
Practical Use Case
// CSV row data
type CsvRow = [string, number, boolean];
const data: CsvRow[] = [
["Mario", 30, true],
["Luigi", 28, false],
["Peach", 25, true],
];
// Destructuring tuples
const [name, age, active] = data[0];
console.log(name); // "Mario"
Readonly Tuples
const coords: readonly [number, number] = [10, 20];
coords[0] = 30; // ❌ Error — readonly
Key Takeaways
- Tuples have fixed length and typed positions
- Each position must match its declared type
- Great for CSV data, coordinates, and function returns
- Named tuples improve readability