A tuple is a special array type in TypeScript with a fixed number of elements where each element position has an explicit, distinct type.
flowchart LR
subgraph Tuple ["Tuple: [number, string, boolean]"]
0["Index 0: number"]
1["Index 1: string"]
2["Index 2: boolean"]
end
// Fixed-length HTTP response tuple: [statusCode, message, isSuccess]
type HttpResponse = [number, string, boolean];
function fetchUserData(id: number): HttpResponse {
if (id === 1) {
return [200, "User found successfully", true];
}
return [404, "User not found", false];
}
const [code, statusMessage, ok] = fetchUserData(1);
console.log(`HTTP ${code}: ${statusMessage} (Success: ${ok})`);
// Named tuple elements for enhanced readability
type Coordinate = [latitude: number, longitude: number, altitude?: number];
const officeLocation: Coordinate = [37.7749, -122.4194];
console.log(`Latitude: ${officeLocation[0]}, Longitude: ${officeLocation[1]}`);
[x: number, y: number]) provides IDE documentation without affecting runtime behavior.Array.prototype.push() on Tuples: TypeScript permits .push() on non-readonly tuples by default! Use readonly [number, string] to prevent modification.useState hook [value, setter]).Define a tuple type UserCredentials representing [username: string, userId: number]. Create a valid tuple variable matching this definition.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With