TypeScript Tuples
A tuple is a special type in TypeScript that allows you to express an array with a known number of elements and types. Unlike regular arrays, the type of each element at each position in a tuple is fixed.
Declaring and Initializing Tuples
You can define a tuple by specifying a series of types in square brackets [].
Accessing Tuple Elements
You can access elements in a tuple using indexes, just like accessing array elements. TypeScript will provide the correct type hints based on the index.
Destructuring Assignment with Tuples
You can use destructuring assignment to conveniently get all elements from a tuple.
Optional Tuple Elements
Tuple elements can also be optional by adding ? after the type. Optional elements must be at the end of the tuple.
Tuples vs Arrays Comparison
Out-of-Bounds Access to Tuples
In earlier versions of TypeScript, out-of-bounds operations on tuples (like pushing a new element) were allowed, but when accessing this out-of-bounds element, its type would be treated as a union type of all possible types in the tuple.
However, as TypeScript has evolved, type checking for tuples has become increasingly strict. Now, it's generally not recommended to perform operations like push that change the tuple's length, as this violates the "fixed length" principle of tuples.
Common Use Cases
-
Multiple return values from functions: When a function needs to return multiple values of different types, tuples are a good choice.
-
Representing key-value pairs: When handling data like what
Object.entries()returns.