Code Lab

First item

EasyTypeScript types4 min

Write a function first(items) that returns the first item of an array, or undefined if the array is empty. Do not change the array.

The result type must follow the array. For an array of numbers it is number | undefined, for an array of strings string | undefined. Replace unknown in the starter code. Do not change the code at the bottom, each line after @ts-expect-error must stay a type error.

Examples

first([3, 1, 2])

Returns 3

The first item of an array of numbers.
first(['a', 'b'])

Returns 'a'

For strings the result is a string.
first([])

Returns undefined

An empty array has no first item.

Source

Function
Loading the editor...
  1. Inputfirst([ 3, 1, 2 ])
    Expected3
  2. Inputfirst([ 'a', 'b' ])
    Expected'a'
  3. Inputfirst([])

Hidden tests run on Submit.