Getting Started with TypeScript Generics
August 19, 2026
- TypeScript
Getting Started with TypeScript Generics
Generics let a function, type, or class work with more than one type
while still being fully type-checked. They're what makes Array<string>
and Array<number> both valid without TypeScript defining Array twice.
The problem generics solve
Without generics, you're stuck choosing between duplicating code per type
or giving up type safety with any:
function firstStringElement(arr: string[]): string {
return arr[0];
}
function firstNumberElement(arr: number[]): number {
return arr[0];
}A generic function
A type parameter — conventionally T — lets one function definition cover
every type, while TypeScript still infers and checks the specific type at
each call site:
function firstElement<T>(arr: T[]): T {
return arr[0];
}
const a = firstElement([1, 2, 3]); // inferred as number
const b = firstElement(['x', 'y']); // inferred as stringNo any involved — a is typed number, b is typed string, and
TypeScript caught that automatically from the argument you passed in.
Generic interfaces
interface ApiResponse<T> {
data: T;
error: string | null;
}
async function getUser(id: string): Promise<ApiResponse<User>> {
const res = await fetch(`/api/users/${id}`);
return res.json();
}ApiResponse<T> describes the shape once, and every endpoint plugs in
its own payload type — ApiResponse<User>, ApiResponse<Post[]> — without
redefining data and error each time.
Constraining a type parameter
Sometimes T needs to guarantee it has a certain shape. extends narrows
what's allowed:
interface HasId {
id: string;
}
function findById<T extends HasId>(items: T[], id: string): T | undefined {
return items.find((item) => item.id === id);
}Now findById only accepts arrays of objects that have an id: string
property — and inside the function, item.id is known to exist.
Default type parameters
interface Cache<T = unknown> {
get(key: string): T | undefined;
set(key: string, value: T): void;
}
const stringCache: Cache<string> = new Map();
const anyCache: Cache = new Map(); // falls back to unknownMultiple type parameters
function merge<T, U>(a: T, b: U): T & U {
return { ...a, ...b };
}
const merged = merge({ name: 'Alice' }, { age: 30 });
// merged: { name: string } & { age: number }When to reach for generics
Use a generic when a function's return type — or an interior type, like an array element — depends on what's passed in. If a function always works with the same concrete type, a generic just adds noise; save it for code that's genuinely reused across types.