Typed Collections and Fixed Structures
Learn how to work with arrays and tuples in TypeScript. This module explains typed arrays, readonly arrays, and tuples with practical examples and real-world use cases.
1. Typed Arrays
Typed arrays allow you to define the type of elements an array can hold. This ensures consistency and prevents invalid data from being added.
Array of Numbers
Array of Strings
Generic Array Syntax
Both syntaxes are valid and commonly used in real projects.
Type Safety Example
The second push causes a compile-time error because the array accepts only numbers.
2. Readonly Arrays
Readonly arrays prevent modification of array elements after initialization. They are useful when data should not be changed accidentally.
Readonly Array Example
The following operations are not allowed:
ReadonlyArray Type
Readonly arrays are commonly used for configuration values and constants.
3. Tuples and Use Cases
Tuples allow you to define an array with a fixed number of elements, where each element has a specific type.
Basic Tuple Example
The order and type of values must match the tuple definition.
Accessing Tuple Values
Tuple with Optional Elements
Real-World Use Cases for Tuples
Tuples are commonly used for:
- Returning multiple values from a function
- Representing fixed-structure data such as database records
- Working with key-value pairs
Example Function Returning a Tuple
Conclusion
Arrays and tuples are essential data structures in TypeScript. Typed arrays ensure consistency, readonly arrays protect data integrity, and tuples provide a structured way to handle fixed-length data. Understanding these concepts helps build safer and more predictable applications.