...

/

Creating generic functions

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.

Generic function syntax

We define the type parameters for a generic function in angle-brackets before the function’s parentheses:

function someFunc<T1, T2, ...>(...) {
  ...
}
...