Get the length of TypeScript tuples at the type level. Learn about tuple types and the length property in this easy-level challenge on TypeScriptPro.
Count tuple elements at compile time with TypeScript's type system! 📏
This easy-level challenge teaches you to create a generic Length<T>
that returns the length of a tuple as a literal number type. You'll discover how TypeScript tuples have a special length
property that contains the exact count of elements, unlike regular arrays.
This challenge is perfect for understanding the difference between arrays and tuples in TypeScript, and how to leverage tuple-specific properties in your type-level programming.
For this challenge, you will need to change the following code to make the tests pass (no type check errors).
For given a tuple, you need create a generic Length
, pick the length of the tuple
For example:
type tesla = ['tesla', 'model 3', 'model X', 'model Y']
type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']
type teslaLength = Length<tesla> // expected 4
type spaceXLength = Length<spaceX> // expected 5
The solution is elegantly simple, leveraging TypeScript's built-in tuple length property.
type Length<T extends readonly unknown[]> = T['length']
Why this works:
length
propertyT['length']
accesses this property at the type level['a', 'b', 'c']
, the length is the literal type 3
readonly unknown[]
constraint ensures T is an array-like typeThis showcases a fundamental difference between tuples and arrays: tuples have a fixed, known length at compile time, while arrays have number
as their length type.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount
This challenge is originally from here.