12 - Reading Real Codebases
📋 Jump to Takeaways🎁 TypeScript syntax and type theory are one thing. Reading a real production codebase — with decorators, branded types, middleware chains, and deeply nested generics — is another. This lesson is a guided tour of the patterns that actually show up.
You know the syntax. You know the type system. Now you need to read other people's code. These are the patterns you'll actually see in TypeScript backend codebases.
Middleware Chains
Middleware is a function that runs before your handler. It can modify the request/response, then call next() to continue the chain, or stop it.
Here's the Hono style (similar to Express):
import { Hono } from "hono";
import type { Context, Next } from "hono";
const app = new Hono();
// Middleware: runs on every request
async function logger(c: Context, next: Next): Promise<void> {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${c.req.method} ${c.req.path} - ${ms}ms`);
}
// Middleware: auth check
async function requireAuth(c: Context, next: Next): Promise<void | Response> {
const token = c.req.header("Authorization");
if (!token) {
return c.json({ error: "Unauthorized" }, 401); // return a response to stop the chain
}
await next();
}
app.use("*", logger);
app.use("/api/*", requireAuth);
app.get("/api/users", (c) => {
return c.json({ users: [] });
});
// Request to /api/users hits: logger -> requireAuth -> handlerIt's just function composition. Each function decides whether to call next() or stop. The types enforce the signature.
Express looks similar but uses (req, res, next) instead of (c, next):
import type { Request, Response, NextFunction } from "express";
function logger(req: Request, res: Response, next: NextFunction): void {
console.log(`${req.method} ${req.path}`);
next();
}When you see middleware in a codebase, trace the chain. Find where use() is called to see what runs before your handler.
Generic API Clients
Most codebases wrap fetch with a typed client. You'll see this pattern constantly.
class ApiClient {
constructor(private baseUrl: string) {}
async get<T>(path: string): Promise<T> {
const res = await fetch(`${this.baseUrl}${path}`);
if (!res.ok) {
throw new Error(`GET ${path} failed: ${res.status}`);
}
return res.json() as Promise<T>;
}
async post<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(`${this.baseUrl}${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
throw new Error(`POST ${path} failed: ${res.status}`);
}
return res.json() as Promise<T>;
}
}interface User {
id: string;
name: string;
email: string;
}
const api = new ApiClient("https://api.example.com");
// T is inferred as User
const user = await api.get<User>("/users/123");
console.log(user.name); // fully typed
// T is inferred as User
const created = await api.post<User>("/users", {
name: "Alice",
email: "[email protected]",
});
console.log(created.id); // fully typedThe generic <T> lets callers specify what type they expect back. The client doesn't know or care about the shape.
res.json() as Promise<T> is a type assertion. The runtime doesn't validate anything. For actual safety, combine this with Zod validation (next section).
Zod Validation
Zod defines a schema and infers the TypeScript type from it. One source of truth for runtime validation and compile-time types.
import { z } from "zod";
// Define the schema
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email(),
role: z.enum(["admin", "user"]),
createdAt: z.coerce.date(),
});
// Infer the type FROM the schema
type User = z.infer<typeof UserSchema>;
// Result type:
// {
// id: string;
// name: string;
// email: string;
// role: "admin" | "user";
// createdAt: Date;
// }// Validate incoming data
function parseUser(data: unknown): User {
return UserSchema.parse(data);
// Throws ZodError if validation fails
// Returns typed User if valid
}
// Safe version that doesn't throw
function tryParseUser(data: unknown) {
const result = UserSchema.safeParse(data);
if (result.success) {
console.log(result.data.name); // typed as User
} else {
console.log(result.error.issues); // validation errors
}
}This pattern is everywhere in modern TS backends. API route handlers, config loading, environment variable parsing, anywhere external data enters your system.
// Validate environment variables at startup
const EnvSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().default(3000),
NODE_ENV: z.enum(["development", "production", "test"]),
});
const env = EnvSchema.parse(process.env);
// env.PORT is number, env.DATABASE_URL is string
// Crashes at startup if env vars are missing/invalidCrash at startup, not at 3am when a request hits a missing config value.
Builder Pattern
Method chaining with return this. You'll see this in query builders, config objects, and test fixtures.
class QueryBuilder<T extends Record<string, unknown>> {
private table: string;
private conditions: string[] = [];
private limitVal?: number;
private orderByVal?: string & keyof T;
constructor(table: string) {
this.table = table;
}
where(condition: string): this {
this.conditions.push(condition);
return this;
}
limit(n: number): this {
this.limitVal = n;
return this;
}
orderBy(field: string & keyof T): this {
this.orderByVal = field;
return this;
}
toSQL(): string {
let sql = `SELECT * FROM ${this.table}`;
if (this.conditions.length > 0) {
sql += " WHERE " + this.conditions.join(" AND ");
}
if (this.orderByVal) {
sql += ` ORDER BY ${this.orderByVal}`;
}
if (this.limitVal) {
sql += ` LIMIT ${this.limitVal}`;
}
return sql;
}
}The generic T constrains orderBy to only accept actual field names of the entity type. This is how generics add safety to builder patterns.
interface User { id: number; name: string; active: boolean; created_at: string }
const query = new QueryBuilder<User>("users")
.where("active = true")
.orderBy("created_at") // TS ensures this is a key of User
.limit(10)
.toSQL();
console.log(query);
// SELECT * FROM users WHERE active = true ORDER BY created_at LIMIT 10The return type is this, not QueryBuilder. That means subclasses preserve their own type through the chain. You'll see this in ORMs like Drizzle and Kysely.
Repository/Service Pattern
Most TS backends separate data access (repository) from business logic (service). Standard layered architecture.
// repository: talks to the database
import { db } from "./db.js";
import { users } from "./schema.js";
import { eq } from "drizzle-orm";
export class UserRepository {
async findById(id: string) {
const result = await db
.select()
.from(users)
.where(eq(users.id, id));
return result[0] ?? null;
}
async create(data: { name: string; email: string }) {
const result = await db
.insert(users)
.values(data)
.returning();
return result[0];
}
}// service: business logic, calls repository
import { UserRepository } from "./user-repository.js";
export class UserService {
constructor(private repo: UserRepository) {}
async getUser(id: string) {
const user = await this.repo.findById(id);
if (!user) throw new Error(`User ${id} not found`);
return user;
}
async createUser(name: string, email: string) {
// business rules go here
if (!email.includes("@")) {
throw new Error("Invalid email");
}
return this.repo.create({ name, email });
}
}// route handler: wires it together
import { Hono } from "hono";
import { UserService } from "./user-service.js";
import { UserRepository } from "./user-repository.js";
const userService = new UserService(new UserRepository());
const app = new Hono();
app.get("/users/:id", async (c) => {
const user = await userService.getUser(c.req.param("id"));
return c.json(user);
});The service takes the repository as a constructor argument. Pass a mock repository in tests, the real one in production. Easy.
Common Conventions
These show up in almost every TS codebase.
Type-Only Imports
// Regular import: included in runtime output
import { UserService } from "./user-service.js";
// Type-only import: erased at compile time
import type { User } from "./types.js";Use import type when you only need the type for annotations, not the value at runtime. Smaller compiled output, fewer circular dependency issues.
Barrel Files (index.ts)
// lib/index.ts
export { UserService } from "./user-service.js";
export { AuthService } from "./auth-service.js";
export type { User, Session } from "./types.js";// Clean import from the barrel
import { UserService, AuthService } from "./lib/index.js";
import type { User } from "./lib/index.js";Barrel files create a public API for a directory. Look for index.ts files to understand what a module exposes.
Named Exports Over Defaults
Most TS codebases use named exports exclusively.
// Preferred: named export
export class UserService { /* ... */ }
export function createUser() { /* ... */ }
// Avoided: default export
export default class UserService { /* ... */ }Named exports are refactor-friendly. Rename the export and every import breaks with a clear error. Default exports can be imported as any name, so renames are invisible.
How to Read Unfamiliar TypeScript
When you land in a new codebase, follow this order.
Start with the types. Find types.ts or the types/ directory. Read the interfaces and type aliases. They tell you what data flows through the system.
// Reading this tells you more than 100 lines of implementation
interface Order {
id: string;
userId: string;
items: OrderItem[];
status: "pending" | "paid" | "shipped" | "delivered";
total: number;
createdAt: Date;
}Find the entry point. Check package.json scripts or the framework's routing setup. In SvelteKit, it's src/routes/. In Express/Hono, search for new Hono() or express().
Follow the data flow. Pick one API endpoint. Trace it from the route handler, through the service layer, to the database query. Read the types at each boundary.
Check the barrel files. index.ts files tell you what each directory considers its public API. Start there, not with internal files.
Read the tsconfig. It tells you the project's strictness level, module system, and path aliases. Five minutes reading tsconfig.json saves an hour of confusion.
Branded Types
TypeScript's structural type system means two types with the same shape are interchangeable. That's usually fine, but not when you have multiple string IDs that must never be mixed up. Branded types add a phantom property to enforce nominal-style distinctions.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function getUser(id: UserId) { /* ... */ }
const userId = "u-123" as UserId;
const orderId = "o-456" as OrderId;
getUser(userId); // ✅
getUser(orderId); // ❌ Type 'OrderId' is not assignable to type 'UserId'
getUser("u-123"); // ❌ plain string not acceptedGo developers will recognize this as analogous to type UserId string — a named type that doesn't implicitly convert. Java developers will recognize it as a wrapper value object without the boilerplate. You'll encounter this pattern in production TypeScript backends wherever ID confusion would cause silent data corruption.
Key Takeaways
- Middleware is function composition. Trace the
use()calls to understand what runs before your handler. - Generic API clients use
<T>to let callers specify return types. The client doesn't validate the shape at runtime. - Zod gives you one source of truth: define a schema, infer the type. Use it everywhere external data enters your system.
- The builder pattern uses
return thisfor method chaining. Thethisreturn type preserves subclass types. - Repository/service separation is the standard architecture. Services hold business logic, repositories handle data access.
- Use
import typefor type-only imports. It avoids circular deps and reduces output size. - When reading new code: start with types, find the entry point, follow one request through the layers.