Arrays and tuples are key data structures in TypeScript for storing sets of values. Understanding how to define and use them is fundamental for type safety and clarity in your code.
Defining Arrays
Arrays hold multiple values of the same type. You can define arrays using either the type[] notation or the Array<type> generic form.
Example:
// Using type[]
const numbers: number[] = [1, 2, 3];
// Using Array<type>
const fruits: Array<string> = ["apple", "banana", "mango"];
Defining Tuples
Tuples allow you to store a fixed number of elements where each element may be of a different type.
Example:
// Tuple - [string, number]
const user: [string, number] = ["Alice", 25];
// Tuple with more elements
const point: [number, number, number] = [3, 4, 5];
Key Differences
- Arrays: All elements are of the same type.
- Tuples: Each position has a specific type and length is fixed.
When to Use Which?
- Use arrays when you have a collection of items of the same type.
- Use tuples when you have a fixed structure with known types per position.
Defining arrays and tuples properly helps TypeScript catch errors early and keeps your data structures clear and predictable.
Top comments (0)