A Tuple in TypeScript is a special type of array where:
- Order matters
- Fixed number of elements
- Each position can have a different data type
Basic Syntax
let user: [string, number];
user = ["Raj", 25];
Here:
- First value →
string - Second value →
number
Why Tuple?
Normal arrays allow any order:
let arr: (string | number)[] = [25, "Raj"];
But tuple keeps strict order:
let user: [string, number];
user = ["Raj", 25]; // ✅
user = [25, "Raj"]; // ❌ Error
Real-world Example
User Information
let employee: [number, string, boolean];
employee = [101, "Amit", true];
Meaning:
- ID → number
- Name → string
- Active status → boolean
Accessing Tuple Values
let student: [string, number] = ["Rahul", 90];
console.log(student[0]); // Rahul
console.log(student[1]); // 90
Tuple with Optional Values
let user: [string, number?];
user = ["Raj"];
user = ["Raj", 25];
? means optional.
Readonly Tuple
let color: readonly [string, string] = ["red", "blue"];
// color[0] = "green"; ❌ Error
Tuple with Destructuring
let person: [string, number] = ["Raj", 25];
let [name, age] = person;
console.log(name);
console.log(age);
Tuple in Function Return
Very common in real projects.
function getUser(): [string, number] {
return ["Raj", 25];
}
const [name, age] = getUser();
Difference Between Array and Tuple
| Feature | Array | Tuple |
|---|---|---|
| Size | Dynamic | Fixed |
| Order | Not important | Important |
| Types | Same or mixed | Fixed per position |
| Example | string[] | [string, number] |
Interview Definition
A Tuple in TypeScript is a fixed-size typed array where each element can have a different data type and specific position.