A tuple in TypeScript is a specialized array type that enforces a fixed length and a specific type sequence. It allows you to express an array where the type of each element is known at a specific positional index, enabling strict type checking for heterogeneous collections.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Basic Syntax and Assignment
A tuple is defined by wrapping a comma-separated list of types in square brackets. The assigned array must exactly match the defined length and the type at each corresponding index.Positional Type Inference
When accessing elements via bracket notation or destructuring, the TypeScript compiler infers the exact type based on the index. Accessing an index outside the defined length results in a compile-time error.Optional Elements
Tuple elements can be marked as optional using the? modifier. Optional elements must always appear at the end of the tuple declaration. This makes the length property of the tuple a union type.
Variadic Tuples (Rest Elements)
Tuples can incorporate rest elements (...) to represent an open-ended sequence of a specific type while maintaining strict positional types for the other elements. The rest element can be positioned at the beginning, middle, or end of the tuple.
Labeled (Named) Tuple Elements
To improve code readability and tooling support (like IDE autocompletion), tuple elements can be labeled. These labels are purely metadata and do not affect the runtime behavior or the underlying type structure.Readonly Tuples
By default, tuple elements are mutable. You can enforce immutability using thereadonly modifier or the Readonly<T> utility type. This removes mutating methods like push, pop, and splice from the type definition.
The Mutation Caveat
In standard (non-readonly) tuples, TypeScript strictly enforces length and types during direct assignment. However, array mutation methods likepush() and pop() are permitted by the compiler, provided the pushed value matches the union type of all tuple elements. Despite this, TypeScript will still prevent access to out-of-bounds indices.
Master TypeScript with Deep Grasping Methodology!Learn More





