First of Array
Implement a generic First
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:
T extends any[]
- This constraint ensures that T must be an array type.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
- TypeScript Utility Types
- [Type Challenges: First of Array](https://github.com/type-challenges/type-challenges/blob/main/questions/00014-easy-first/README.md