What is a Tuple in TypeScript?
In TypeScript, a tuple is a type of array with a fixed number of elements, where each element can have a different type. Tuples are used when you want to represent a collection of values with a specific order and a known number of values.
Syntax
Tuples are defined using square brackets with each element's type specified:
type StringNumberPair = [string, number];
In the example above, StringNumberPair
is a tuple type that consists of a string
followed by a number
.
Using Tuples
Tuples are particularly useful for functions that return multiple values. Consider a function that returns both a status message and a status code:
function getStatus(): [string, number] { return ["Success", 200]; } const status = getStatus(); console.log(status[0]); // Output: "Success" console.log(status[1]); // Output: 200
Advantages of Tuples
- Type Safety: Tuples provide type safety by ensuring that each element in the tuple is of the expected type.
- Clarity: They make the structure of the data clear, especially when dealing with multiple return values from functions.
- Order and Length: The order and length of a tuple are fixed, which helps prevent errors related to accessing elements that do not exist.
Limitations
- Immutability: By default, tuples are mutable. However, you can use the
readonly
modifier to make them immutable. - Destructuring: Tuples can be destructured, but the destructuring assignment must match the structure of the tuple:
const [message, code] = getStatus(); console.log(message); // Output: "Success" console.log(code); // Output: 200
Conclusion
Tuples in TypeScript offer a powerful way to handle collections of different types with fixed sizes. They improve code readability and maintainability by enforcing strict types and order for collections of values.