TypeScript Type Challenge First of Array Walkthrough

| 1 min read

The goal of the challenge is to implement a generic type called First that takes an array and returns the type of the first element in the array.

The challenge: https://github.com/type-challenges/type-challenges/blob/main/questions/00014-easy-first/README.md

Watch the video

An example case

For example, given the following cases, our First type should return the type shown in the comments:

First<[3, 2, 1]> // 3
First<[() => 123, { a: string }]> // () => 123
First<[]> // never
First<[undefined]> // undefined

Approach

Like in the Tuple To Object, we're interested in the type of a specific element of an array. We can use indexed access types to do this.

We know we can access the type of the first element in an array with T[0] so our initial implementation can be as simple as:

  type First<T extends any[]> = T[0]

This works for 3 out of 4 of our example cases above, but fails for the empty case First<[]>. We can see that:

First<[]>

is currently returning undefined but the challenge requires it to return never.

The solution

We can special case the empty array and use conditional types to solve this challenge. We want to say

if the array is empty, return never, otherwise return the type of the first element in our array

The syntax for conditional types looks like:

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

Where T extends [] can be read as, if T is empty.