A tuple is a specific type of array. It's a fixed-size, ordered array of elements where the type of each element is known.
Tuple syntax
The tuple syntax is slightly similar to an array and is made up of the square brackets ([
and ]
) containing an entry for each tuple item. So, a tuple of 3 string elements would look like this:
Tuple benefits
- Type Safety: Tuples help ensure that each element in your array is the right type. Imagine telling a list exactly what type of information should go, like a slot for a name (text) and another for an age (number).
- Clarity: Using tuples, your code tells a clear story about what kind of data it expects. It's like labelling boxes before moving; you know exactly what goes inside each one.
- Fixed Size: Tuples are like fixed-size suitcases; you can only pack a certain number of items. This makes your data predictable and easy to manage.
- Easy to Use with Other Features: They play well with TypeScript's cool tricks, like pulling elements out into variables or combining tuples, making your coding life easier and more efficient.
Recap
- A tuple is a specific type of array.
- A tuple is a fixed-size, ordered array of elements where the type of each element is known.
- A tuple is made up of the square brackets (
[
and ]
) containing an entry for each tuple item. - Tuple syntax (
[string, string]
) vs. array syntax (string[]
). The tuple in this example is limited to two items of type string
. The array can accept as many string
items as you want. - TypeScript understands the type of each tuple item. This reduces type-related bugs.