TypeScript · Lesson 2

Generics

Type parameters, constraints, keyof and T[K], inference, const type parameters and generic higher-order functions.

5 min read

In short

  • Generics relate inputs to outputs, so types aren't lost
  • Let inference pick T; explicit arguments are rare
  • A type parameter should appear at least twice
  • extends constraints unlock properties of T
  • keyof T and T[K] give typed property access

A generic is a function (or type) that is parameterised by a type, so it can describe a relationship between its inputs and outputs. That relationship is the whole point: function first(xs: unknown[]): unknown works for any array but forgets everything; function first<T>(xs: readonly T[]): T | undefined works for any array and remembers.

Generic functions and inference

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

first([1, 2, 3]);          // T inferred as number
first<string>(['a']);      // explicit type argument (rarely needed)
first([1, 'a']);           // T inferred as string | number

TypeScript infers T mainly from the arguments. Only when the arguments don't determine it does it fall back to the type the result is expected to have (const ids: Set<string> = new Set()), as a lower-priority source. Prefer letting inference work; explicit type arguments are a sign the signature could be better. (const user: User = parse(body) with a parse<T>(): T signature is the same unchecked cast in disguise.)

A useful rule: a type parameter should appear at least twice (an input and the output, or two inputs). If it appears once, it isn't relating anything. This one is a lie dressed up as type safety:

▶ Try
function parse<T>(json: string): T { return JSON.parse(json); } // caller picks T, nothing checks it
const user = parse<User>(body);   // just an `as User` cast in disguise

Constraints: extends

A constraint says what a type parameter must at least be, which unlocks operations on it:

▶ Try
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest([1, 2], [3]);        // number[]
longest(['a'], ['b', 'c']);  // string[]
// longest(1, 2);            // error: number has no 'length'

Note that the return type is T, not { length: number }: the constraint only states what T must at least have (formally, an upper bound: T must be assignable to it), and the caller keeps the specific type.

keyof and indexed access T[K]

keyof T is the union of T's keys; T[K] is the type of the property at key K. Together with a constraint they give you type-safe property access:

▶ Try
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user = { id: 1, name: 'Ada', admin: true };
getProp(user, 'name');    // string
getProp(user, 'admin');   // boolean
// getProp(user, 'email'); // error: not assignable to "id" | "name" | "admin"

Because K is inferred as the literal 'name', T[K] resolves to exactly string. If you pass a union of keys you get a union of value types. T[number] on an array or tuple gives its element type.

Multiple type parameters and defaults

▶ Try
function mapValues<T, U>(obj: Record<string, T>, fn: (value: T, key: string) => U): Record<string, U> {
  const out: Record<string, U> = {};
  for (const [k, v] of Object.entries(obj)) out[k] = fn(v, k);
  return out;
}

interface ApiResponse<TData, TError = string> {   // default type argument
  data?: TData;
  error?: TError;
}
type R = ApiResponse<User>;                       // TError = string

Inference runs left to right through context: T is fixed from obj, then the callback is checked with value: T, and U is inferred from what the callback returns. That ordering is why APIs put the data first and callbacks last.

Generic interfaces, type aliases and classes

▶ Try
interface Repository<T extends { id: string }> {
  get(id: string): Promise<T | undefined>;
  save(entity: T): Promise<void>;
}

class TypedMap<K, V> {
  private readonly map = new Map<K, V>();
  set(key: K, value: V): this { this.map.set(key, value); return this; }
  get(key: K): V | undefined { return this.map.get(key); }
}

Class type parameters are fixed when the instance is created (new TypedMap<string, number>(), or inferred from constructor arguments). Methods can add their own type parameters on top, which is how a typed event emitter lets on('login', ...) and on('logout', ...) take different payloads.

const type parameters (TS 5.0)

Inference widens literals in mutable positions: ['a', 'b'] becomes string[]. Adding const to a type parameter asks for the narrowest type, as if the caller had written as const:

▶ Try
function routes<const T extends readonly string[]>(paths: T): T { return paths; }
const r = routes(['/home', '/about']);   // readonly ["/home", "/about"]

Prefer a readonly array constraint. It accepts both mutable and readonly arrays from callers, and it is what const inference naturally produces (with a mutable string[] constraint, current versions infer a mutable tuple, but early 5.x versions silently fell back to string[]).

Generic higher-order functions

To wrap any function while preserving its signature, capture the parameter list as a tuple:

▶ Try
function logged<A extends unknown[], R>(fn: (...args: A) => R, label: string): (...args: A) => R {
  return (...args) => {
    console.log(label, args);
    return fn(...args);
  };
}
const add = (a: number, b: number) => a + b;
const loggedAdd = logged(add, 'add'); // (a: number, b: number) => number

A extends unknown[] is inferred as the labelled tuple [a: number, b: number], so callers even keep the parameter names. This is the basis of debounce, memoize, retry and middleware typings.

Gotchas and techniques

  • NoInfer<T> (TS 5.4) stops a position from contributing to inference: function createFSM<S extends string>(states: S[], initial: NoInfer<S>) makes initial be checked against states rather than widening S.
  • Partial inference doesn't exist. You cannot write f<User>(...) and let the other parameters infer. The standard workaround is currying: createStore<User>()(initialState).
  • Generic narrowing is limited. Inside function f<T extends string | number>(x: T), checking typeof x === 'string' narrows x, but TypeScript will not narrow T itself, so returning a value "of type T" often needs a cast. Overloads or a non-generic implementation are sometimes cleaner.
  • {} is not "empty object". It means "any non-nullish value". Use object or Record<string, unknown> as constraints.
  • In .tsx files, write <T,>(x: T) => x for generic arrow functions so the parser doesn't read <T> as JSX.

In real codebases

Side note

Generics are everywhere at the edges of a system: typed API clients (client.get('/users/:id') returning that route's response type), repositories, state stores, event buses, form libraries, dependency injection. Good library signatures follow a few habits: infer instead of asking for type arguments, constrain only as much as needed, put inference sources (data) before consumers (callbacks), and return types that are computed from inputs rather than declared by the caller.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app