Defining Tuple Types Explicitly
What you'll learn: How to create tuple types with precise type annotations for each position, giving you full control over the exact shape of your fixed-length arrays.
While TypeScript can sometimes infer tuple types, you'll often need to define them explicitly to get the exact type safety you want. Explicit tuple type definitions let you specify the type at each position, creating a contract that must be followed.
Basic Explicit Tuple Type Syntax
You define a tuple type by listing the types for each position inside square brackets:
let userRecord: [string, number, boolean];
userRecord = ["Alice", 30, true]; // ✓ Valid
userRecord = [30, "Alice", true]; // ✗ Error: types in wrong order
The tuple type [string, number, boolean] explicitly declares that the first element must be a string, the second a number, and the third a boolean. Order matters—TypeScript enforces this at compile time.
Why Define Explicitly?
Without an explicit annotation, TypeScript might infer a regular array type instead of a tuple:
const coords = [10, 20]; // Inferred as: number[]
coords.push(30); // ✓ Allowed, but might not be what you want
const point: [number, number] = [10, 20]; // Tuple type
// point.push(30); // Still allowed at runtime, but type indicates 2 elements
Explicit tuple types document your intent: this isn't just "an array of numbers," it's specifically "a pair of coordinates."
Using Tuple Types in Functions
Tuple types shine when defining function signatures:
function getUserInfo(): [string, number] {
return ["Bob", 25];
}
const [name, age] = getUserInfo(); // name: string, age: number
Each position has its own type, giving you type safety during destructuring.
Key Takeaway: Explicitly defining tuple types with syntax like [string, number, boolean] gives you precise control over fixed-length array structures, ensuring each position holds exactly the type you expect and documenting your code's intent clearly.