TypeScript Tuple Type
Tuples are fixed-length arrays with predefined types and order, ideal for grouping heterogeneous data.
How to Define Tuples
let user: [string, number];
user = ["Alice", 25];
The 'user' tuple includes a string (name) and a number (age). Incorrect or missing elements cause errors.
Function Return Values with Tuples
function getUser(): [string, boolean] {
return ["Bob", true];
}
Tuples allow returning multiple typed values from functions, keeping data structured and meaningful.
Using Destructuring with Tuples
const [name, isActive] = getUser();
Tuples work well with array destructuring for meaningful variable names.
Why Use Tuples for Fixed Data?
Tuples are great for fixed data structures like coordinates or HTTP response tuples, ensuring type and order safety.
Difference Between Tuples and Arrays
Arrays do not enforce element count or type order, whereas tuples enforce both strictly.
Back