TypeScript Tuples
A tuple is a typed array with a pre-defined length and types for each index.
28th August 2022
Time to read: 1 min
To define a tuple, specify the type of each element in the array:
let ourTuple: [number, boolean, string];
// initialize correctly
ourTuple = [5, false, 'Apple']; // OK
ourTuple = [false, 5, 'Apple']; // Error
When accessing an element with a known index, the correct type is retrieved:
// OK
console.log(ourTuple[2].substring(1));
// Error
console.log(ourTuple[1].substring(1));
Property 'substring' does not exist on type 'number'.
Readonly Tuple
A good practice is to make your tuple readonly
.
// define our readonly tuple
const ourReadonlyTuple: readonly [number, boolean, string] = [5, true, 'Orange'];
// throws error as it is readonly.
ourReadonlyTuple.push('Red');
Destructuring Tuples
Since tuples are arrays we can also destructure them.
const graph: [number, number] = [55.2, 41.3];
const [x, y] = graph;