ORMs and Query Builders
You'll learn: How to build type-safe database query builders that infer result types based on which columns you select.
The Problem with Untyped Queries
When you query a database, you typically select specific columns. Without generics, you'd get back a generic "row" type containing all columns, even if you only selected two. This forces unsafe casting or defeats TypeScript's safety entirely.
Generic Query Builders to the Rescue
ORMs (Object-Relational Mappers) and query builders use generics to derive the result type from what you actually select. When you write .select('name', 'email'), generics can infer a return type containing only those two properties.
Here's the fundamental pattern:
interface User {
id: number;
name: string;
email: string;
age: number;
}
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
function select<T, K extends keyof T>(
columns: K[]
): Pick<T, K>[] {
// In real code: execute query
return [] as Pick<T, K>[];
}
// Type: Pick<User, "name" | "email">[]
// Which equals: { name: string; email: string; }[]
const users = select<User, 'name' | 'email'>(['name', 'email']);
The K extends keyof T constraint ensures you can only select columns that actually exist on your table type. The return type Pick<T, K>[] contains only those selected properties—exactly matching your query.
This pattern scales to .where(), .join(), and .orderBy() methods, each adding type information that flows through the query chain. Libraries like Prisma and Drizzle use sophisticated versions of this to provide completely type-safe database queries.
Key Takeaway: Generic query builders use keyof constraints and mapped types to return precisely-typed results matching your selected columns, catching typos and schema mismatches at compile time.