- A tuple is an array with a fixed number of elements, where each element has a specific type. Unlike arrays, tuples allow you to store values of different types at specific positions.
- To declare a tuple type, you use square brackets `[]` and specify the types of the elements in order, separated by commas. Here's an syntax:
- Example:
- In this example:
- The first element must be a string (name).
- The second element must be a number (age).
- You can access tuple elements just like array elements, using their indices.
- In the example above, `tuple` is declared as a tuple with three elements. The first element is a string, the second element is a number, and the third element is a boolean.
- You can access individual elements of a tuple using zero-based indexing:
- Tuple types can be useful when you want to represent a collection of values with different types, but the number of elements and their types are fixed and known.
- You can also modify the values in a tuple, but you need to ensure that the new values conform to the types defined for each position in the tuple.
- TypeScript supports optional elements in tuples, meaning that some elements may or may not be present. This is done using the ? symbol.
- It's worth noting that TypeScript also provides additional utility types for working with tuples, such as `readonly`, `Partial`, and `Pick`. These utility types can help you define more specific constraints and transformations on tuples.
Feature |
Array |
Tuple |
Type of elements |
Homogeneous (all elements have the
same type) |
Heterogeneous (different types at
specific positions) |
Length |
Can be of any length |
Fixed number of elements |
Index Access |
Can access any index |
Access based on predefined types |
Example |
let arr: number[] = [1, 2, 3]; |
let tuple: [string, number] =
["John", 30]; |
- Arrays: Useful when you need to store a list of items that are all of the same type.
- Tuples: Helpful when you want to store a fixed number of elements with different types (like representing a person's name and age).
No comments:
Post a Comment