Extract the first element type from TypeScript arrays and tuples. Master indexed access types and conditional types in this easy-level challenge on TypeScriptPro.
Get the first element's type from any array with this foundational challenge! 🥇
In this easy-level challenge, you'll implement a generic First<T>
that extracts the type of the first element from an array. This seemingly simple task introduces important concepts like indexed access types, conditional types for handling empty arrays, and working with array types in TypeScript.
Understanding how to access and manipulate array element types is crucial for building more complex type utilities. You'll also learn how to handle edge cases like empty arrays gracefully.
For this challenge, you will need to change the following code to make the tests pass (no type check errors).
Implement a generic First<T>
that takes an Array T
and returns its first element's type.
For example:
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
There are multiple ways to solve this challenge, each teaching different TypeScript concepts.
Solution using infer:
type First<T extends any[]> = T extends readonly [infer First, ...infer _Rest]
? First
: never
Key concepts:
infer First
captures the first element's typeinfer _Rest
captures the rest of the array elements' typesT extends readonly [infer First, ...infer _Rest]
pattern matches the array type? First
returns the first element's type if the array is not empty: never
returns never
if the array is emptyAlternative solution using indexed access:
type First<T extends any[]> = T extends readonly [...any[]] ? T[0] : never
Key concepts:
T[0]
accesses the type at index 0never
infer F
captures the first element's type[infer F, ...any[]]
destructures the array typeBoth approaches effectively extract the first element's type while handling empty arrays appropriately.
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.