#18Easy

Length of Tuple

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.

Challenge Instructions: Length of Tuple

Easy

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

Change the following code to make the test cases pass (no type check errors).

Loading...

Video Walkthrough

Detailed Explanation

The solution is elegantly simple, leveraging TypeScript's built-in tuple length property.

[object Object]

Why this works:

This 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.

Share this challenge