Declaring Tuple Types
You'll learn: How to explicitly define tuple types using bracket notation with types at each position.
While arrays in TypeScript hold multiple values of the same type, tuples let you specify exactly what type each position holds. To declare a tuple type, you use square brackets with the type for each element in order.
The Basic Syntax
To declare a tuple type, list each position's type inside square brackets, separated by commas:
let user: [string, number];
user = ["Alice", 30]; // ✓ Valid
user = [30, "Alice"]; // ✗ Error: types are in wrong order
The order matters! The first element must be a string, and the second must be a number.
Multiple Element Tuples
You can declare tuples with as many positions as you need:
let coordinates: [number, number, number];
coordinates = [10, 20, 30]; // ✓ Valid (x, y, z)
let employee: [string, number, boolean];
employee = ["Bob", 45, true]; // ✓ Valid (name, age, isActive)
Think of It Like a Contract
Imagine a form with specific labeled fields: "Name (text)", "Age (number)", "Active (yes/no)". A tuple type is like that form—each position has a predetermined type that you must follow. Unlike arrays where every element is the same type, tuples say "position 0 is this type, position 1 is that type."
Why Explicit Declaration Matters
Without the type annotation, TypeScript would infer a regular array type or a union:
let data = ["Hello", 42]; // Inferred as (string | number)[]
let typed: [string, number] = ["Hello", 42]; // Explicitly a tuple
Key Takeaway: Declare tuple types using bracket syntax with each position's type listed in order: [string, number, boolean] creates a three-element tuple with specific types at each index.