Advertisement
Advanced TypeScript, Primitive Types, Arrays & Tuples

How would you write a generic type that extracts the length of a tuple type at compile time?

Short answer

Since tuple types carry a real '.length' property whose VALUE is a specific literal number (not just 'number' like regular arrays), you can access it directly via an indexed access type on the tuple's 'length' key to extract that literal numeric type.

Save TypeScript mock interview
Advertisement
AModel answer
Since tuple types carry a real '.length' property whose VALUE is a specific literal number (not just 'number' like regular arrays), you can access it directly via an indexed access type on the tuple's 'length' key to extract that literal numeric type.
type TupleLength<T extends readonly unknown[]> = T['length'];
type Len = TupleLength<[string, number, boolean]>; // 3 (the literal number type, not just 'number')
Real-world example
Building advanced type-level utilities (like a type-safe zip or curry function) that need to reason about a tuple's exact arity at compile time.
Likely follow-ups
  • Does this same 'length' trick work identically for a plain array type like number[], or does it behave differently?
Related topics