Search⌘ K
AI Features

Creating generic functions

Explore how to create generic functions in TypeScript for React development. Learn to define type parameters, use generics in functions and arrow functions, and understand type inference to write reusable, strongly-typed functions that work with multiple data 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, ...>(...) {
  ...
}
...