TypeScript Tuples
A tuple is an array with a fixed type for each position. The order of the types in the annotation matters.
Read a tuple by index
The first position holds text. The second position holds a number.
let user: [string, number] = ["Ada", 36];
console.log(user[0]);
console.log(user[1]);Swapped values are refused
The two values below trade places. The first position now holds the wrong type.
let user: [string, number] = [36, "Ada"];
console.log(user);Push past the end
push adds a value after the last position here. The compiler allows the call.
let pair: [string, number] = ["Ada", 36];
pair.push("extra");
console.log(pair.length);
console.log(pair);Example
let result: [string, number] = ["Ada", 95];
console.log(`${result[0]} scored ${result[1]}`);Key points
- A tuple fixes the type of each position.
- Square brackets with one type per position write a tuple type.
- An index in square brackets reads one position.
- An assignment must match the type at each position.
In this example, the tuple pairs a name with a score. The first position holds the name Ada. The second position holds the number 95. The log line builds one sentence from both positions.
Note
push can add a value past the end of a tuple and the length grows to match.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
In the tuple type [string, number], what type must the second value have?