Skip to content

First of Array

Implement a generic First 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

Solution

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

This implementation works as follows:

  1. T extends any[] - This constraint ensures that T must be an array type.
  2. T extends [] ? never : T[0] - This checks if T is an empty array. If it is, it returns never (since there’s no first element). Otherwise, it returns the type at index 0 of the array.
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type emptyArr = []

type head1 = First<arr1> // 'a'
type head2 = First<arr2> // 3
type headEmpty = First<emptyArr> // never

References