Skip to main content

First of Array

introduction#

Implement a generic First<T> that takes an Array T and returns it's 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'
type head2 = First<arr2>; // expected to be 3
ts
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

start point#

ts
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[]>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[undefined]>, undefined>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try
ts
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = any;
 
/* _____________ Test Cases _____________ */
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[]>, never>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<First<[undefined]>, undefined>>
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
];
Try

my solution#

Spoiler warning // Click to reveal answer
ts
// type First<T extends any[]> = T[number] extends never ? never : T[0]
// type First<T extends any[]> = T extends [infer F, ...infer L] ? F : never
type First<T extends any[]> = T extends [] ? never : T[0];
Try
ts
// type First<T extends any[]> = T[number] extends never ? never : T[0]
// type First<T extends any[]> = T extends [infer F, ...infer L] ? F : never
type First<T extends any[]> = T extends [] ? never : T[0];
Try
Checkout more Solutions