All academies
All challenges

Generic First Element

easygenerics50 XP

Problem

Write a generic function firstElement<T>(items: T[]): T | undefined that returns the first element of an array, or undefined when the array is empty. Calling it with number[] must return a number-typed result, and with string[] a string-typed result — no any allowed.

Expected output

10
a
undefined

Hints

Stuck? Reveal hints one at a time.

Solution

Try solving it yourself first — revealing is always available.

Press Run in the editor — your console output is checked automatically.
No errors
Loading...

Console output appears here. Press Run or just type — the code compiles automatically.