#14Easy

First of Array

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

Challenge Instructions: First of Array

Easy

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

Video Walkthrough

Detailed Explanation

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:

Alternative solution using indexed access:

type First<T extends any[]> = T extends readonly [...any[]] ? T[0] : never

Key concepts:

Both approaches effectively extract the first element's type while handling empty arrays appropriately.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount

This challenge is originally from here.