TypeScript Generics: A Practical Guide for Backend Developers
Generics let you write reusable, type-safe code without duplicating functions or using any.
The Basics
function getFirst<T>(items: T[]): T | undefined { return items[0]; }
const num = getFirst([1, 2, 3]); // type: number
Generic API Response
interface ApiResponse<T> { data: T; meta: { page: number; total: number }; }
async function fetchPaginated<T>(url: string): Promise<ApiResponse<T>> {
return (await fetch(url)).json();
}
Generic Repository
class Repository<T extends HasId> {
constructor(private collection: string) {}
async findById(id: string): Promise<T | null> {
return db.collection(this.collection).findOne({ id });
}
async create(data: Omit<T, "id">): Promise<T> {
const doc = { ...data, id: randomUUID() } as T;
await db.collection(this.collection).insertOne(doc);
return doc;
}
}
Utility Types
- Partial, Pick, Omit, Record
Part of my Production Backend Patterns series. Follow for more practical backend engineering.
Top comments (0)