This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for TypeScript puzzle on BFE.dev
21. implement LastItem<T>

Solution:

type LastItem<T extends any[]> = T extends [...infer _, infer Last] ? Last : never;

// Test cases
type A = LastItem<[string, number, boolean]> // boolean
type B = LastItem<['B', 'F', 'E']> // 'E'
type C = LastItem<[]> // never

Explanation:

  • This solution uses an array spread pattern to split the tuple type into two parts: all elements except the last one (denoted by ...infer _) and the last element (denoted by infer Last).
  • The conditional type then returns the Last type if it exists, or never if the tuple is empty (i.e., []).