Extracting Tuple Length
You'll learn how to use TypeScript's type system to extract and work with tuple lengths at compile time, enabling powerful type-level computations.
When you work with tuples in TypeScript, the type system knows the exact length at compile time. You can extract and use this length information in your types using the length property combined with indexed access types.
The Core Pattern
Just like you can access a property on an object type with bracket notation, you can access the length property of a tuple type:
type MyTuple = [string, number, boolean];
type Length = MyTuple['length']; // type Length = 3
This works because tuple types have a numeric literal type for their length property, unlike regular arrays which have length: number.
Why This Matters
Extracting tuple length lets you:
- Build type-level functions that depend on tuple sizes
- Create constraints based on tuple dimensions
- Generate new tuple types with specific lengths
- Enforce compile-time length requirements
Comparing Tuples and Arrays
// Tuple: length is a literal number type
type FixedTuple = [string, number];
type TupleLength = FixedTuple['length']; // 2
// Array: length is just 'number'
type DynamicArray = string[];
type ArrayLength = DynamicArray['length']; // number
Using Length in Generic Constraints
type HasLength3<T extends [any, any, any]> = T['length']; // Always 3
type CheckLength<T extends readonly any[]> = T['length'];
type A = CheckLength<[1, 2, 3]>; // 3
type B = CheckLength<[boolean]>; // 1
The readonly any[] constraint accepts any tuple, and the indexed access T['length'] extracts its specific length.
Key Takeaway: TypeScript's type system tracks exact tuple lengths as numeric literal types, which you can extract using T['length'] for compile-time length-based type operations.