Generic functions

Topic 1 of 3 in Generics6 min readIntermediateFree course

Overview

Some functions don’t care what type of data they handle: getting the first item of an array, removing duplicates, grouping, caching. You could type them with unknown or any, but then the caller loses the type. Generics let you write the function once and keep the exact types for every caller.

The problem

TypeScript
function first(items: unknown[]): unknown {
  return items[0];
}

const n = first([10, 20]);
n.toFixed(2);
// error TS18046: 'n' is of type 'unknown'.

Typing it with unknown is safe but useless: the information that this was an array of numbers is lost. Typing it with any throws away checking entirely. And writing firstNumber, firstString, firstUser… doesn’t scale.

Type parameters

Generics: types as parameters. In function first<T>(items: T[]): T | undefined, <T> declares a type parameter. The input (T[]) and the output (T | undefined) both use it, so whatever goes in decides what comes out: first([10, 20]) sets T = number and returns number | undefined; first([“a”, “b”]) sets T = string and returns string | undefined; first<User>(users) sets T = User explicitly and returns User | undefined. TypeScript infers T from each call, so one function keeps the exact types for every caller.

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

const n = first([10, 20]);        // number | undefined
const s = first(["a", "b"]);      // string | undefined
const u = first(users);           // User | undefined

<T> declares a type parameter — a variable that holds a type instead of a value. Each call chooses what T is. Because the same T appears in the parameter (T[]) and the return type (T | undefined), TypeScript knows that what comes out matches what went in.

T is just a conventional name. Use descriptive names when it helps: <Item>, <TKey, TValue>.

Inference and explicit type arguments

TypeScript infers type arguments from the values you pass, so you rarely write them. You can specify them:

TypeScript
first<number>([10, 20]);
first<string>([10, 20]);
// error TS2322: Type 'number' is not assignable to type 'string'.

Explicit type arguments are useful when there’s nothing to infer from — for example, an empty array, or a function whose type parameter only appears in the return type:

TypeScript
const ids = new Set<string>();             // nothing to infer from yet
const data = await fetchJson<User[]>(url); // (more on this pattern in Validating external data)

Generic arrow functions

TypeScript
const last = <T,>(items: readonly T[]): T | undefined => items[items.length - 1];

The trailing comma in <T,> is only needed in .tsx files, where <T> alone would look like a JSX tag.

Several type parameters

TypeScript
function zip<A, B>(as: A[], bs: B[]): [A, B][] {
  return as.slice(0, bs.length).map((a, i) => [a, bs[i] as B]);
}

zip(["Asha", "Ben"], [29, 34]);   // [string, number][]

Generic callbacks

Generics are especially powerful with callbacks: the type flows into the callback, and the callback’s return type flows out:

TypeScript
function mapValues<T, R>(items: T[], transform: (item: T) => R): R[] {
  return items.map(transform);
}

mapValues(["a", "bb"], (s) => s.length);   // number[] — s: string, R inferred as number

That’s exactly how the built-in Array.prototype.map is typed. Look at a few built-in signatures by hovering — map, filter, reduce, Promise.all, Object.fromEntries — and you’ll see generics everywhere.

Generics vs unknown vs any

Input Output Caller gets
(x: any) => any anything any no checking at all
(x: unknown) => unknown anything unknown safe, but must re-check
<T>(x: T) => T anything the same type the exact type back

Generics are the right choice when there’s a relationship between types — between input and output, or between several parameters.

When not to use generics

A type parameter that appears only once isn’t relating anything:

TypeScript
function logValue<T>(value: T): void {   // T used once
  console.log(value);
}

function logValue(value: unknown): void { // simpler, same effect
  console.log(value);
}

Rule of thumb: every type parameter should appear at least twice — usually once in the parameters and once in the return type. If you can’t say what a type parameter connects, remove it.

Also avoid generics whose type the caller must always specify by hand, like parse<T>(json: string): T. That’s just a type assertion in disguise: parse<User>(text) checks nothing at run time. Return unknown and validate instead.

Remember: a type parameter is a type-level variable. Declare it in <…>, use it to connect inputs to outputs, and let TypeScript infer it at each call.

Exercise

A generic toolbox

Write four generic functions and prove their types with annotated variables: (1) last<T>(items: readonly T[]): T | undefined; (2) groupBy<T>(items: readonly T[], keyOf: (item: T) => string): Record<string, T[]>; (3) uniqueBy<T, K>(items: readonly T[], keyOf: (item: T) => K): T[] that keeps the first item for each key; (4) zip<A, B>(as: readonly A[], bs: readonly B[]): [A, B][] that stops at the shorter array. Use them on the people array: the last person’s name, people grouped by city, people unique by city, and names zipped with ages. Print each result.

TypeScript
type Person = { name: string; age: number; city: string };

const people: Person[] = [
  { name: "Asha", age: 29, city: "Pune" },
  { name: "Ben", age: 34, city: "Leeds" },
  { name: "Chen", age: 41, city: "Pune" },
  { name: "Dee", age: 25, city: "Lagos" },
];

// 1. last

// 2. groupBy

// 3. uniqueBy

// 4. zip

Summary

  • A type parameter (<T>) is a placeholder for a type, chosen separately for each call.
  • TypeScript infers type arguments from the values you pass — you rarely write first<number>(…).
  • Use the type parameter in both input and output to connect them; that’s what makes a function generic rather than unknown-typed.
  • Functions can have several type parameters (<A, B>), and generic callbacks pass precise types through.
  • If a type parameter appears only once, you probably don’t need it — use a concrete type or unknown.