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 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 5Change the following code to make the test cases pass (no type check errors).
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 3readonly 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.
This challenge is originally from here.
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