What is a tuple in TypeScript, and how is it different from an array?
A tuple is an array with a fixed length where each position has its own type, like [string, number]. A normal array type such as (string | number)[] allows any length and any order of those types.
Explain it simply
A cricket scorecard line reads "Kohli, 82": a name first, then a number, always in that order and always two items. That is a tuple. A shopping list of any number of items is an array.
Tuples are useful when a function returns a small, fixed group of values, which is exactly what React's useState does. You can also name the positions to make the code readable.
Example
const row: [string, number] = ["Kohli", 82];
// const bad: [string, number] = [82, "Kohli"]; // Error: order matters
// const long: [string, number] = ["Kohli", 82, 1]; // Error: length is 2
const [name, runs] = row; // destructuring keeps each type
type Range = [start: number, end?: number]; // labels and an optional slot
function minMax(nums: number[]): [number, number] {
return [Math.min(...nums), Math.max(...nums)];
}
const [lo, hi] = minMax([4, 9, 2]);
const mixed: (string | number)[] = ["Kohli", 82, 90]; // plain array, any lengthWhat to say in the interview
"A tuple fixes both the length and the type at each index, so [string, number] is exactly a string then a number. An array like (string | number)[] has no such guarantee. I use tuples for small fixed results such as a hook returning [value, setter], and objects once there are more than two or three fields."
Common mistakes
- Expecting a tuple to stop push(); tuples are mutable unless marked readonly.