First of Array
introduction#
Implement a generic First<T> that takes an Array T and returns it's first element's type.
For example
tstype 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
tstype 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#
tsTry/* _____________ Your Code Here _____________ */typeFirst <T extends any[]> = any;Â/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>];
tsTry/* _____________ Your Code Here _____________ */typeFirst <T extends any[]> = any;Â/* _____________ Test Cases _____________ */typecases = [Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.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>>];
my solution#
Spoiler warning // Click to reveal answer
tsTry// type First<T extends any[]> = T[number] extends never ? never : T[0]// type First<T extends any[]> = T extends [infer F, ...infer L] ? F : nevertypeFirst <T extends any[]> =T extends [] ? never :T [0];
tsTry// type First<T extends any[]> = T[number] extends never ? never : T[0]// type First<T extends any[]> = T extends [infer F, ...infer L] ? F : nevertypeFirst <T extends any[]> =T extends [] ? never :T [0];