A tuple is a typed array with a fixed length and specific types for each element.
Tuples are useful because they let you define the type of each element in the array.
To define a tuple, specify the type for each element in the array:
// define our tuple let ourTuple: [number, boolean, string]; // initialize correctly ourTuple = [5, false, ‘Coding God was here’]; |
As you can see, we have a number, a boolean, and a string. But what happens if we try to assign them in the wrong order:
// define our tuple let ourTuple: [number, boolean, string]; // initialized incorrectly which throws an error ourTuple = [false, ‘Coding God was mistaken’, 5]; |
Although we have a boolean, a string, and a number, the order of these elements is crucial in a tuple and will result in an error if mismatched. |
It’s good practice to make your tuple readonly.
Tuples only have strictly defined types for their initial values.
// define our tuple let ourTuple: [number, boolean, string]; // initialize correctly ourTuple = [5, false, ‘Coding God was here’]; // We have no type safety in our tuple for indexes 3+ ourTuple.push(‘Something new and wrong’); console.log(ourTuple); |
Notice that tuples only have strongly defined types for their initial values.
// define our readonly tuple const ourReadonlyTuple: readonly [number, boolean, string] = [5, true, ‘The Real Coding God’]; // throws error as it is readonly. ourReadonlyTuple.push(‘Coding God took a day off’); |
If you’ve used React, you’ve probably worked with tuples. The useState hook returns a tuple containing the current value and a setter function. For example, const [firstName, setFirstName] = useState(‘Dylan’) is a common pattern. Given this structure, we know the first element of the tuple will be a specific type—in this case, a string—and the second element will be a function. |
Named tuples enable us to provide context for each value at its respective index.
const graph: [x: number, y: number] = [55.2, 41.3]; |
Named tuples offer greater context by specifying what each index value represents. |
Since tuples are arrays, they can also be destructured.
const graph: [number, number] = [55.2, 41.3]; const [x, y] = graph; |