Generic types
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 type aliases
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:
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 recursiveGeneric interfaces
Interfaces take type parameters the same way:
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 | undefinedDefault type parameters
Type parameters can have defaults, just like function parameters:
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 typeParameters 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:
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:
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:
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.
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.
// 1. Page<T> and paginate
// 2. Result<T, E> and parseAge
// 3. Cache<V>// 1. Page<T> and paginate
type Page<T> = { items: T[]; page: number; totalPages: number };
function paginate<T>(all: readonly T[], page: number, size: number): Page<T> {
const start = (page - 1) * size;
return { items: all.slice(start, start + size), page, totalPages: Math.ceil(all.length / size) };
}
// 2. Result<T, E> and parseAge
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };
function parseAge(text: string): Result<number> {
const age = Number(text);
if (!Number.isInteger(age) || age < 0 || age > 150) {
return { ok: false, error: `"${text}" is not a valid age` };
}
return { ok: true, value: age };
}
// 3. Cache<V>
class Cache<V> {
private readonly entries = new Map<string, V>();
set(key: string, value: V): void {
this.entries.set(key, value);
}
get(key: string): V | undefined {
return this.entries.get(key);
}
get size(): number {
return this.entries.size;
}
}
const letters = ["a", "b", "c", "d", "e", "f", "g"];
const page2: Page<string> = paginate(letters, 2, 3);
console.log(page2); // { items: [ 'd', 'e', 'f' ], page: 2, totalPages: 3 }
for (const input of ["42", "abc"]) {
const result = parseAge(input);
console.log(result.ok ? `age ${result.value}` : result.error);
}
const prices = new Cache<number>();
prices.set("tea", 3.5);
prices.set("cake", 5.25);
console.log(prices.get("tea"), prices.size); // 3.5 2
// @ts-expect-error -- the cache only holds numbers
prices.set("pie", "4.75");Summary
- Type aliases, interfaces and classes can take type parameters:
type Page<T> = { items: T[] }. - A generic type is a template —
Page<User>andPage<Product>are different, fully checked types. - Type parameters can have defaults:
Result<T, E = string>. Array<T>,Promise<T>,Map<K, V>,Set<T>andRecord<K, V>are built-in generic types.- Generic classes keep one type per instance: a
Cache<number>only accepts numbers.