TypeScript Tuples

TypeScript Tuples
Number of elements is fixed
Type of each element is predefined
Order cannot be changed
Tuples are useful when you need a structured collection of values.
Declaring a Tuple
Index
0→ numberIndex
1→ string
Invalid:
Tuple with More Elements
Tuple with Optional Elements
Readonly Tuples
Prevents modification.
Not allowed:
Named Tuple Elements (Recommended)
Improves readability.
Tuple Destructuring
Tuple vs Array
A tuple is a fixed-length array where each element has a specific type and position, whereas an array can have any number of elements of the same type. In a tuple, the order and type of values are strictly defined. In an array, elements are generally of one common type and the length can change dynamically. Tuples are useful when returning multiple related values with different types, while arrays are better for collections of similar data.
| Feature | Tuple | Array |
|---|---|---|
| Length | Fixed | Dynamic |
| Type | Fixed per index | Same type |
| Order | Important | Not strict |
| Use Case | Structured data | Lists |
Tuple in Functions
Tuple with Rest Elements
Tuple Summary
Tuples in TypeScript provide a way to define fixed-length arrays with predefined types for each position. They ensure type safety, maintain order, and are useful for returning multiple values from functions. Destructuring improves readability, and rest elements add flexibility. Tuples are ideal when structure and order matter, while arrays are better for uniform, dynamic collections.
| Feature | Example |
|---|---|
| Basic Tuple | [number, string] |
| Optional | [number, string?] |
| Readonly | readonly [number, number] |
| Named | [id: number, name: string] |
| Rest | [string, ...number[]] |
Best Practices
- Use tuples for fixed structured data
- Prefer named tuple elements
- Use
readonlyfor safety - Avoid tuples for large dynamic lists
