Creating generic functions

In this lesson, we will learn how to create strongly-typed functions with flexible parameters and return types.

A non-generic function #

Below is a function that takes in an array and returns its first element. If the array is empty, null is returned.

function firstOrNull(array: string[]): string | null {
  return array.length === 0 ? null : array[0];

This function is strongly-typed, which is excellent; but what if we need to do the same thing for an array of numbers? We can’t use the above function because it is restricted for arrays of strings. Wouldn’t it be nice if we could pass the array item type into this function? Well, this is what generic functions allow us to.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy