Generics: Reusable Types

<T> for reusable types. Generic functions, generic classes, and constraining generics with extends.

Step 1 of 6

The motivation: don’t lose information

Without generics, a function that returns the first item of an array is forced to either:

  • Lock to a specific type (function first(arr: number[]): number) — only works for numbers.
  • Use any or unknown — works for everything but loses the type information the caller had.

Generics let the function say: "I don’t care what T is, but the array of Ts I take and the T I return have to be the same type."

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

This is exactly how Array.prototype.map is typed in TypeScript’s built-in library — generic over the element type.

Learn more on MDN
TYPESCRIPTREAD ONLY