Skip to content
LumenaryAcademy
Practice 60 min

Generics

Functions, types and classes with type parameters, constraints with extends and keyof, and the habits that keep generic code readable.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Code that works for any type, without forgetting which

The last lesson ended with a problem. A helper like once works for any function, and so its parameter can't name one specific function type; but typing it with any loses every bit of information, and the result is unchecked. The same problem appears whenever code is reusable: a function that returns the first element of any array, a stack of any kind of item, a cache, a retry wrapper, an event emitter.

Generics solve it. A generic function has type parameters, placeholders such as T that stand for "whatever type the caller uses". The caller doesn't usually write them: TypeScript infers them from the arguments, and then the return type follows. first([3, 1, 4]) is known to return a number, first(["Ana"]) a string, from one definition. Every collection in the standard library is generic, Array<T>, Map<K, V>, Promise<T>, which is why map, get and await have known types. This lesson shows how to write your own.

Worked examplesH

Generic functions

Definition— type parameter

A type parameter, declared in angle brackets after a function's name (function first<T>(...)) or a type's name (interface Page<T>), is a variable that ranges over types. Each use of the function or type supplies a type argument for it, written explicitly (first<number>(...)) or, for functions, usually inferred from the arguments.

typescript
// Generic functions: type parameters capture the relationship between inputs and outputs.
function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}

const n = first([3, 1, 4]);          // number | undefined
const s = first(["Ana", "Bo"]);      // string | undefined
console.log(n?.toFixed(1), s?.toUpperCase());

// The `once` helper, now typed properly: the wrapper has exactly the wrapped function's type.
function once<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R {
  let done = false;
  let result: R;
  return (...args: Args): R => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}

const connect = once((host: string, port: number) => `connected to ${host}:${port}`);
console.log(connect("db.local", 5432));
console.log(connect("elsewhere", 1));   // same answer: runs only once

// groupBy for any element type and any key.
function groupBy<T, K extends PropertyKey>(items: readonly T[], keyOf: (item: T) => K): Record<K, T[]> {
  const groups = {} as Record<K, T[]>;
  for (const item of items) {
    const key = keyOf(item);
    (groups[key] ??= []).push(item);
  }
  return groups;
}

const rivers = [
  { name: "Niger", continent: "Africa" as const, km: 4180 },
  { name: "Volga", continent: "Europe" as const, km: 3531 },
  { name: "Congo", continent: "Africa" as const, km: 4700 },
];
const byContinent = groupBy(rivers, (r) => r.continent);   // Record<"Africa" | "Europe", ...>
console.log(byContinent.Africa.map((r) => r.name), byContinent.Europe.length);

// Explicit type arguments, when inference has nothing to go on.
const ids = new Set<string>();
ids.add("u-1");
console.log(ids.size, first<number>([]));

export {};
text
3.0 ANA
connected to db.local:5432
connected to db.local:5432
[ 'Niger', 'Congo' ] 1
1 undefined
  • first<T>: the parameter items: readonly T[] ties T to the element type of whatever array is passed, and the return type T | undefined reuses it. From [3, 1, 4], TypeScript infers T = number.
  • once has two type parameters: Args, the tuple of the wrapped function's parameter types, and R, its return type. The wrapper's type (...args: Args) => R is therefore exactly the wrapped function's type: connect takes (host: string, port: number) and returns a string, and calling it with wrong arguments is an error. The constraint Args extends unknown[] says Args must be some array (tuple) type, which a rest parameter requires. This is how utility libraries type their higher-order functions.
  • groupBy works for any element type T and any key type K (constrained to PropertyKey, the built-in alias for string | number | symbol). Because the callback returns a literal "Africa" | "Europe" here, the result is a record with exactly those keys. (ECMAScript 2024 added a built-in Object.groupBy, which TypeScript's es2024 library types almost the same way, except that it returns Partial<Record<K, T[]>>, honestly admitting that some keys may have no group. This simpler version trusts every key to appear. This course's checks compile against the es2023 library, so the program writes its own.)
  • Arrow functions can be generic too: const firstOf = <T>(items: readonly T[]): T | undefined => items[0];. In .tsx files, where <T> could be mistaken for a JSX tag, the convention is to write <T,> with a trailing comma.
  • Explicit type arguments are needed when nothing can be inferred: new Set<string>() creates an empty set that will hold strings, and first<number>([]) says what the empty array would have contained.

Generics are TypeScript's version of parametric polymorphism, one of the central ideas of type theory (Lumenary Math's type theory): a function that behaves the same way for every type, and whose type says so.

IntuitionH

Constraints, keyof and indexed access

An unconstrained T could be anything, so you can do almost nothing with it: not read a property, not call a method. A constraint, T extends Something, limits which types may be used, and in return lets the function use what Something guarantees.

typescript
// Constraints: "T can be anything that has...", and keyof for property names.
function longest<T extends { length: number }>(a: T, b: T): T {
  return b.length > a.length ? b : a;
}
console.log(longest("kiwi", "papaya"), longest([1, 2], [3]));

// keyof T is the union of T's property names; T[K] is the type of property K.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

interface Country {
  name: string;
  capital: string;
  population: number;
  landlocked: boolean;
}
const nepal: Country = { name: "Nepal", capital: "Kathmandu", population: 30_500_000, landlocked: true };
const capital = getProperty(nepal, "capital");        // string
const people = getProperty(nepal, "population");      // number
console.log(capital.toUpperCase(), (people / 1e6).toFixed(1));

// A reusable, type-safe sort by any key.
function sortBy<T, K extends keyof T>(items: readonly T[], key: K, direction: "asc" | "desc" = "asc"): T[] {
  const sign = direction === "asc" ? 1 : -1;
  return [...items].sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}

const countries: Country[] = [
  nepal,
  { name: "Chile", capital: "Santiago", population: 19_600_000, landlocked: false },
  { name: "Bolivia", capital: "Sucre", population: 12_400_000, landlocked: true },
];
console.log(sortBy(countries, "population").map((c) => c.name).join(" < "));
console.log(sortBy(countries, "name", "desc").map((c) => c.name).join(", "));

// pluck: the result type follows the key.
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}
const flags: boolean[] = pluck(countries, "landlocked");
console.log(flags);

export {};
text
papaya [ 1, 2 ]
KATHMANDU 30.5
Bolivia < Chile < Nepal
Nepal, Chile, Bolivia
[ true, false, true ]
  • T extends { length: number } accepts strings, arrays and anything else with a numeric length, and preserves which: longest("kiwi", "papaya") returns a string, not a vague "something with a length".
  • keyof T is the union of T's property names: for Country, "name" | "capital" | "population" | "landlocked". T[K], an indexed access type, is the type of property K. Together, in getProperty<T, K extends keyof T>, they make the return type depend on which key is passed: "capital" gives a string, "population" a number. A misspelled key is caught: getProperty(nepal, "mayor") fails with Argument of type '"mayor"' is not assignable to parameter of type 'keyof Country'.
  • sortBy and pluck use the same pattern for real utilities. pluck(countries, "landlocked") returns boolean[] because Country["landlocked"] is boolean. (sortBy compares with < and >, which TypeScript allows for any T[K]; with a key whose values are objects, the comparison would be meaningless, so a production version would constrain the key to properties holding strings or numbers, a technique lesson eight makes possible.)

These patterns are everywhere in typed libraries: an ORM's select("name", "email"), a form library's register("email"), a state store's get("user"), all checked against the property names of your own types.

Worked examplesH

Generic types and classes

Interfaces, type aliases and classes take type parameters too:

typescript
// Generic types and classes: containers that remember what they contain.
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

interface Page<T> {
  items: T[];
  page: number;
  totalPages: number;
}

class Stack<T> {
  #items: T[] = [];
  push(item: T): this {
    this.#items.push(item);
    return this;
  }
  pop(): T | undefined {
    return this.#items.pop();
  }
  peek(): T | undefined {
    return this.#items.at(-1);
  }
  get size(): number {
    return this.#items.length;
  }
}

const undo = new Stack<string>().push("type 'a'").push("type 'b'").push("delete");
console.log(undo.pop(), undo.peek(), undo.size);

// A typed event emitter: each event name has its own payload type.
type Listener<P> = (payload: P) => void;
class Emitter<Events extends Record<string, unknown>> {
  #listeners: { [E in keyof Events]?: Listener<Events[E]>[] } = {};
  on<E extends keyof Events>(event: E, listener: Listener<Events[E]>): void {
    (this.#listeners[event] ??= []).push(listener);
  }
  emit<E extends keyof Events>(event: E, payload: Events[E]): void {
    for (const listener of this.#listeners[event] ?? []) listener(payload);
  }
}

type ShopEvents = {
  added: { sku: string; qty: number };
  checkout: { totalCents: number };
};
const shop = new Emitter<ShopEvents>();
shop.on("added", ({ sku, qty }) => console.log(`added ${qty} x ${sku}`));
shop.on("checkout", ({ totalCents }) => console.log(`paid ${(totalCents / 100).toFixed(2)}`));
shop.emit("added", { sku: "tea", qty: 2 });
shop.emit("checkout", { totalCents: 900 });

// Generic types compose: a page of results, each of which may have failed.
const page: Page<Result<number, string>> = {
  items: [{ ok: true, value: 3 }, { ok: false, error: "timeout" }, { ok: true, value: 4 }],
  page: 1,
  totalPages: 5,
};
const sum = page.items.reduce((acc, r) => (r.ok ? acc + r.value : acc), 0);
console.log(`page ${page.page}/${page.totalPages}: sum ${sum}`);

export {};
text
delete type 'b' 2
added 2 x tea
paid 9.00
page 1/5: sum 7
  • Result<T, E = Error> has a default type argument: Result<number> means Result<number, Error>. Page<T> describes a page of any kind of item. Generic types compose: Page<Result<number, string>> is a page of results that each hold a number or an error message.
  • Stack<T> is a generic class: new Stack<string>() creates a stack whose push accepts only strings and whose pop returns string | undefined. Returning this from push allows the chained calls.
  • Emitter<Events> is the typed event emitter that libraries commonly offer. Events maps each event name to its payload type, and both on and emit are generic in the event name E, so each listener receives exactly the right payload, and a misspelled event or a wrong payload is rejected. In a test file, calling shop.emit("added", { sku: "tea", qty: "two" }) and shop.emit("refund", { totalCents: 100 }) gives:
text
main.ts(11,34): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(12,11): error TS2345: Argument of type '"refund"' is not assignable to parameter of type 'keyof ShopEvents'.

The field #listeners uses a mapped type, { [E in keyof Events]?: Listener<Events[E]>[] }, which builds an object type with one optional property per event; lesson eight is about mapped types.

One detail in this program trips up many people. ShopEvents is declared with type, not interface, because the emitter's constraint is Record<string, unknown>. An object type written as an alias is considered to fit an index signature; an interface is not, since interfaces can be extended later by declaration merging. Declare ShopEvents as an interface with the same two members, and new Emitter<ShopEvents>() is rejected:

text
main.ts(12,29): error TS2344: Type 'ShopEvents' does not satisfy the constraint 'Record<string, unknown>'.
  Index signature for type 'string' is missing in type 'ShopEvents'.

The alternatives are to constrain with object instead, or to use an alias, as here.

ComputationC

Controlling inference: const type parameters and NoInfer

Inference usually guesses right. Two newer features handle the cases where it doesn't.

typescript
// const type parameters (TypeScript 5.0): infer literal types without `as const` at each call.
function defineRoutes<const T extends readonly string[]>(paths: T): T {
  return paths;
}
const routes = defineRoutes(["/", "/about", "/contact"]);   // readonly ["/", "/about", "/contact"]
type Route = (typeof routes)[number];                        // "/" | "/about" | "/contact"

function navigate(to: Route): string {
  return `navigating to ${to}`;
}
console.log(navigate("/about"), routes.length);

// NoInfer (TypeScript 5.4): stop a parameter from widening what T is inferred to be.
function createSelect<T extends string>(options: readonly T[], initial: NoInfer<T>) {
  return { options, value: initial };
}
const size = createSelect(["S", "M", "L"], "M");             // T is "S" | "M" | "L"
console.log(size.value, size.options.join("/"));

export {};
text
navigating to /about 3
M S/M/L

const type parameters (TypeScript 5.0) ask the compiler to infer the narrowest type for an argument, as if the caller had written as const. Without const, defineRoutes(["/", "/about"]) would infer T as string[], and Route would be plain string; with it, the literal paths survive, and navigate("/abuot") becomes an error.

NoInfer<T> (TypeScript 5.4) marks a use of T that should not contribute to inferring it. In createSelect, T should come only from the options; the initial value should be checked against them. Without NoInfer, TypeScript happily infers T from both arguments, and createSelect(["S", "M", "L"], "XL") compiles, with T widened to "S" | "M" | "L" | "XL". With it:

text
main.ts(4,31): error TS2345: Argument of type '"XL"' is not assignable to parameter of type '"S" | "M" | "L"'.
ExplanationH

Reading generic signatures

Much of the generic code you meet will be someone else's: the standard library, a framework, a utility package. Hover over map on an array in your editor and you will see something like map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]. Read it the way the compiler does:

  1. Which type parameters belong to whom? T is the array's own element type, fixed when the array was created (Array<T>). U belongs to map itself and is chosen per call.
  2. Where is each parameter inferred from? U appears in the callback's return type, so it is inferred from what your callback returns.
  3. Where does it flow? U reappears in the result, U[]. So [1, 2].map((n) => String(n)) is a string[].

The same three questions unlock nearly any signature: Promise.all, whose type parameter is a tuple of the promises you pass, so await Promise.all([fetchUser(), fetchOrders()]) gives a correctly typed pair; React's useState<S>(initial: S | (() => S)): [S, Dispatch<SetStateAction<S>>], whose S comes from the initial value; a validation library's parse methods, whose result type comes from the schema object you built. When a signature is too dense to read, look at what the editor shows for a concrete call: the hover over the call displays the type arguments that were inferred, which is often all you need.

When inference picks something too wide or too narrow at a call, you can always pass the type argument explicitly: useState<string | null>(null) says the state will later hold strings, which inference from null alone could never know.

ExplanationH

Writing generics others can read

Generic code is powerful, and it is also the easiest TypeScript to make unreadable. The habits that experienced developers follow:

  • A type parameter should relate two things. If T appears only once in a signature, it is doing nothing that a plain type couldn't: function size<T extends unknown[]>(xs: T): number is just function size(xs: unknown[]): number. The handbook's guidelines for generic functions make the same point: a type parameter that shows up in only one place is almost always unnecessary.
  • Push type parameters down, keep them few. Prefer function first<T>(items: T[]): T to function first<A extends any[]>(items: A): A[number]: both work, but the first reads like what it does, and the compiler infers it more predictably.
  • Use constraints instead of casts. If the body needs item.id, say T extends { id: string }; don't cast inside.
  • Name parameters when there are several. Single letters are conventional for one or two (T, K, V); beyond that, TEvent, TPayload or plain descriptive names (Events, Args, as above) help.
  • Don't return a type parameter you can't produce. function parse<T>(json: string): T { return JSON.parse(json); } looks generic, but it is a type assertion in disguise: the caller picks T, and nothing checks it. Return unknown and validate, as lesson nine does.
  • Let inference work. Writing explicit type arguments at every call is noise; if inference keeps getting them wrong, the signature probably needs restructuring.
Common misconceptionsH

Common misconceptions

Misconception

"Generics exist at run time, as in C# or Java." They are erased like all types. Inside a generic function you cannot ask what T is: there is no typeof T. If behaviour must depend on the type, pass a value (a key, a parser function, a class) that carries the information.

Misconception

"T extends string means T is string." It means T is some type assignable to string: string itself, or a literal like "S", or a union of literals. That is exactly why createSelect can infer "S" | "M" | "L".

Misconception

"any is just as good as a type parameter." any accepts everything and remembers nothing. A type parameter accepts everything and remembers which thing, so that the output type can follow the input.

Misconception

"keyof T is a list of strings." It is a union type of property names, which may include numbers and symbols (keyof of an array type includes number). Use Extract<keyof T, string> (lesson eight) when only string keys will do.

Exercises

Exercises

For type questions, ask what each type parameter is inferred to be at the call, then substitute.

1. Generics

Warm-upComputational

With function first<T>(items: readonly T[]): T | undefined, what is the type of first(["a", "b"])?

2. Generics

CoreComputational

Using the lesson's generic once, what does this print?

let calls = 0;
const square = once((x: number) => {
  calls++;
  return x * x;
});
console.log(square(3), square(4), calls);

3. Generics

CoreComputational

With

interface Country {
  name: string;
  capital: string;
  population: number;
  landlocked: boolean;
}

which string literal types make up keyof Country? List them (without quotes is fine).

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

4. Generics

CoreComputational

With function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] and the Country interface above, what is the type of pluck(countries, "population")?

5. Generics

Warm-upComputational

What does tsc say about getProperty(nepal, "mayor"), where getProperty<T, K extends keyof T>(obj: T, key: K): T[K] and nepal is a Country?

Choose one

6. Generics

CoreComputational

Using the lesson's Stack<T> (with push returning this), what does this print?

const s = new Stack<number>().push(1).push(2).push(3);
const top = s.pop();
s.push(4);
console.log(top, s.size);

7. Generics

StretchHuman

Which of these signatures uses a type parameter that adds nothing and should be simplified?

Choose one

Further reading and resources