Skip to main content

First of Array

Implement a generic First<T> that takes an Array T and returns its first element's type.

For example:

ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
 
type head1 = First<arr1> // expected to be 'a'
Cannot find name 'First'.2304Cannot find name 'First'.
type head2 = First<arr2> // expected to be 3
Cannot find name 'First'.2304Cannot find name 'First'.
ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
 
type head1 = First<arr1> // expected to be 'a'
Cannot find name 'First'.2304Cannot find name 'First'.
type head2 = First<arr2> // expected to be 3
Cannot find name 'First'.2304Cannot find name 'First'.
Solution ✅
ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type arr3 = []
 
type First<A> = A extends [infer First, ...any[]] ? First : never
 
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
type head3 = First<arr3> // expected to be never
ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type arr3 = []
 
type First<A> = A extends [infer First, ...any[]] ? First : never
 
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
type head3 = First<arr3> // expected to be never