This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
19. implement FirstItem<T>
type FirstItem<T extends any[]> = T extends [infer U, ...infer _] ? U : never;// Test Casestype A = FirstItem<[string, number, boolean]>; // stringtype B = FirstItem<['B', 'F', 'E']> // 'B'
The FirstItem
type takes in a tuple T
, and returns the first item of the tuple. It extends any[]
to ensure only tuple types can be passed in.
The implementation uses conditional types to infer the first item of the tuple. If T
is a tuple, it extracts the first item U
using infer
, and returns it. If T
is not a tuple, the type returned is never
.