TypeScript Generics Practice: A first() Function

A generic function works with many types while keeping the relationship between input and output. When you pass numbers, the result type is a number; when you pass strings, it is a string. This exercise writes a small generic helper and checks it with three different arrays.

Before you start: Functions, arrays, indexing and TypeScript type annotations.

Your task

Write a generic function first<T>(items: T[]): T | undefined that returns the first item of an array, or undefined for an empty array. Print the result for a number array, a string array and an empty array.

Starter code

// Write a generic function first<T>(items: T[]): T | undefined.
// Then call it with [10, 20, 30], ["a", "b"] and [] and print each result.

Expected result

10
a
undefined

The quick playground transpiles TypeScript and does not report every type error. Use a full TypeScript project to check the types.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Declare function first<T>(items: T[]): T | undefined and return items[0].

Show the complete solution and walkthrough
// Write a generic function first<T>(items: T[]): T | undefined.
// Then call it with [10, 20, 30], ["a", "b"] and [] and print each result.
function first<T>(items: T[]): T | undefined {
  return items[0];
}
console.log(first([10, 20, 30]));
console.log(first(["a", "b"]));
console.log(first([]));
  1. Put <T> after the function name. T is a placeholder that TypeScript fills in from the argument you pass.
  2. Annotate the parameter as T[] and the return type as T | undefined. Reading items[0] from an empty array gives undefined at runtime.
  3. Call first with numbers, strings and an empty array. The console prints 10, then a, then undefined.

A common mistake

Using any as the return type compiles but loses the link between the input and the output. Omitting undefined from the return type hides the empty-array case from callers.

Try an edge case

first([]) returns undefined. If a real array contains undefined as its first item, the result is also undefined, so the function cannot tell those two cases apart.

Take it one step further

Write a generic last<T>() function, then a function that returns the first item that passes a predicate. Compare their return types.

Read the typescript tool guide