Generic types

Topic 2 of 3 in Generics6 min readIntermediateFree course

Overview

Generic functions keep types flowing through code. Generic types do the same for data structures: you define the shape once, with a placeholder, and fill in the placeholder wherever it’s used. API responses, paginated lists, results, caches, events — anything that wraps “some other type” is a natural generic type.

Generic types are templates. type ApiResponse<T> = { data: T; error: string | null; status: number }; produces ApiResponse<User> with data: User, ApiResponse<Product[]> with data: Product[], and ApiResponse<null> with data: null. Built-in generics you already use: Array<T> (same as T[]), Promise<T> (a T, later), Map<K, V> (keys K to values V), Set<T> (unique Ts) and Record<K, V> (an object with keys K). Write the shape once; plug in a different type each time it is used.

Generic type aliases

TypeScript
type ApiResponse<T> = {
  data: T;
  error: string | null;
  status: number;
};

type UserResponse = ApiResponse<User>;          // data: User
type ProductList = ApiResponse<Product[]>;      // data: Product[]

Without generics you’d write UserResponse, ProductResponse, OrderResponse… each a copy of the same shape. With one generic type, a change (say, adding requestId) applies everywhere.

Other common examples:

TypeScript
type Page<T> = { items: T[]; page: number; totalPages: number };
type Nullable<T> = T | null;
type Pair<A, B> = [A, B];
type Tree<T> = { value: T; children: Tree<T>[] };   // types can be recursive

Generic interfaces

Interfaces take type parameters the same way:

TypeScript
interface Repository<T> {
  findById(id: string): Promise<T | undefined>;
  findAll(): Promise<T[]>;
  save(item: T): Promise<void>;
}

const users: Repository<User> = createUserRepository();
const user = await users.findById("u1");   // User | undefined

Default type parameters

Type parameters can have defaults, just like function parameters:

TypeScript
type Result<T, E = string> =
  | { ok: true; value: T }
  | { ok: false; error: E };

type ParseResult = Result<number>;                 // error: string
type FetchResult = Result<User, { code: number }>; // custom error type

Parameters with defaults must come after those without.

Generic classes

Classes (covered fully in the Classes chapter) can be generic too. Each instance fixes the type:

TypeScript
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }
}

const numbers = new Stack<number>();
numbers.push(1);
numbers.push("2");
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

When the constructor receives a value of type T, TypeScript infers it: new Box(42) is a Box<number>.

The built-in generic types

You’ve been using generic types all along:

Type Meaning
Array<T> / T[] a list of T
ReadonlyArray<T> / readonly T[] a list you can’t change
Promise<T> a T that will arrive later (Promises and async)
Map<K, V> a dictionary from K to V
Set<T> unique values of type T
Record<K, V> an object type with keys K and values V
Partial<T>, Pick<T, K>, … utility types (Utility types)

Generic types that take another type and produce a new one — like Partial<T> — are sometimes called type functions. The Type operators chapter shows how to write your own.

Generic types and generic functions together

Generic functions often return generic types — the type parameter flows straight through:

TypeScript
function ok<T>(value: T): Result<T> {
  return { ok: true, value };
}

const r = ok([1, 2, 3]);   // Result<number[], string>

And when narrowing a generic discriminated union like Result, everything works as with any other union:

TypeScript
if (r.ok) {
  r.value.length;   // number[]
} else {
  r.error;          // string
}

Naming

  • Single letters are conventional for simple cases: T (type), K/V (key/value), E (error), R (result).
  • Use full names when a type has several parameters or the meaning isn’t obvious: Repository<TEntity, TId>.

Remember: whenever you’re about to copy a type and change one inner type, make it generic instead.

Exercise

Pages, results and a typed cache

(1) Define type Page<T> = { items: T[]; page: number; totalPages: number } and write paginate<T>(all: readonly T[], page: number, size: number): Page<T>. (2) Define type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E } and write parseAge(text: string): Result<number> (an integer 0–150). (3) Write a generic class Cache<V> with set(key: string, value: V), get(key: string): V | undefined and a size getter, backed by a Map. Use all three: print page 2 of the letters a–g with size 3, the results of parseAge("42") and parseAge("abc") (value or error), and a Cache<number> holding two prices. Show with // @ts-expect-error that the cache rejects a string.

TypeScript
// 1. Page<T> and paginate

// 2. Result<T, E> and parseAge

// 3. Cache<V>

Summary

  • Type aliases, interfaces and classes can take type parameters: type Page<T> = { items: T[] }.
  • A generic type is a template — Page<User> and Page<Product> are different, fully checked types.
  • Type parameters can have defaults: Result<T, E = string>.
  • Array<T>, Promise<T>, Map<K, V>, Set<T> and Record<K, V> are built-in generic types.
  • Generic classes keep one type per instance: a Cache<number> only accepts numbers.