Tuple Length Inference
What you'll learn: How TypeScript automatically determines and tracks the exact numeric length of tuple types, enabling type-safe length checks and operations.
When you work with variadic tuples, TypeScript doesn't just track what types are in the tuple—it also infers the exact length as a literal number type. This means the .length property becomes a precise numeric literal instead of just number.
How Length Inference Works
TypeScript computes the length by analyzing the tuple structure:
type Pair = [string, number];
// Length is inferred as: 2
type Triple = [boolean, string, number];
// Length is inferred as: 3
type EmptyTuple = [];
// Length is inferred as: 0
When you access .length on a tuple type, you get the exact count as a type:
function getPairLength(pair: [string, number]): 2 {
return pair.length; // Type is literally 2, not number
}
With Optional and Rest Elements
Optional elements add complexity—the length becomes a union:
type OptionalEnd = [string, number?];
// Length could be 1 | 2
type WithRest = [string, number, ...boolean[]];
// Length is: number (because rest can be any length >= 2)
Practical Use with Generics
Length inference shines in generic variadic functions:
function tupleLength<T extends readonly unknown[]>(tuple: T): T['length'] {
return tuple.length;
}
const result = tupleLength(['a', 'b', 'c']); // Type: 3
The return type T['length'] extracts the inferred length literal from the tuple type, giving you compile-time knowledge of tuple sizes.
Key Takeaway: TypeScript infers tuple length as precise numeric literal types, enabling type-safe size validation and allowing you to encode fixed-length constraints directly in the type system—but rest elements collapse length back to number.