Disclosure

Most of the problems under my TypeHero Challenges folder were either obtained from typehero.dev or from type-challenges repo. Purpose of these articles are just to document my approaches for my easy reference. Please visit the respective links for more info.

Link to original

Problem Description

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

Solutions

Approach 1: Using T["length"]

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

Approach 2: Checking for empty array

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

Approach 3: Using infer

type First<T extends any[]> = T extends [infer First, ...any] ? First : never;