First of Array


Problem - On Github

The aim is to accept an array type, and return the value of the first element as a type.

Out initial type given by the puzzle creator is

type First<T extends any[]> = any

Solution

In the Tuple to Object challenge we learnt that you can reference the values of a tuple by the T[number] syntax. So we want to do the same thing but this time we only want the first element. Turns out we can replace number with a specific index and it will give the value.

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

This satisfies most of the conditions, but there is one in the test that looks at what we return when an empty array is used. The challenge author expects never to be returned but out type gives undefined instead.

All we need to do is check if we are given an empty array, and if we are we specifically return never.

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


What to read more? Check out more posts below!