author avatar

aman.suhag

Fri Oct 18 2024

In TypeScript, a tuple is a typed array with a fixed number of elements, where each element may have a different type. Unlike regular arrays, which can hold any number of elements of the same type, tuples define a specific sequence of element types and their corresponding positions.
Key Characteristics of Tuples:
1. Fixed Length: The number of elements in a tuple is fixed. You must specify how many elements the tuple can contain.
2. Different Types: Each element in a tuple can be of a different type. The type for each position is defined.
3. Access by Index: Elements are accessed by their index, just like regular arrays, but the types of the elements at each index are known and enforced by the type system.
let user: [string, number?] = ["Alice"]; // number is optional
#typescript #tuple