There was a type challenge
The task was to create a generic function called First that takes an array T and returns the type of its first element.
type arr1 = ["a", "b", "c"];
type arr2 = [3, 2, 1];
type head1 = First<arr1>; // expected: 'a'
type head2 = First<arr2>; // expected: 3
I found it confusing as the requirement was to return the type of the first element. So shouldn't the output be string
for the first case and number
for the second?
What am I missing?
P.S. The given solution returns "a" instead of string.
type First<T extends any[]> = T extends [] ? never : T[0];
Update:
In the following code snippet, head1
is inferred as string
.
let arr1 = ["a", "b", "c"]; // using let instead of type
type head1 = First<typeof arr1>;
Why is it that when I use type array1
as in my initial question, head1
is inferred as "a", but when using above code, it's inferred as "string"?