Get the First Item, Typed by Length

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write first(list): return the list's first item, or undefined when it's empty. Use overloads so the type says when undefined is possible: a tuple known to have at least one item ([T, ...T[]], readonly or not) gives T, and any other list gives T | undefined.

Your code must pass

  • Returns the first item
  • Returns undefined for an empty list
  • Has no type errors
  • A non-empty tuple gives the item type
  • Any other list may give undefined
  • Works on readonly lists