Level 20
Real-World Projects
Bring everything together: structure a production TypeScript application, type its API boundaries honestly, share types across layers, and use types to make tests sharper rather than noisier.
30 min read + quiz
Structuring a TypeScript Application
Organize by feature, not by kind. A features/billing folder holding its routes, services, and types beats parallel routes/, services/, types/ trees where one change touches four distant folders. Feature folders keep the blast radius of a change small and make ownership obvious.
Types live next to the code they describe, with one exception: types shared across layers or packages (domain models, API contracts) get a dedicated home — a shared/types folder or, in a monorepo, a dedicated package — so that dependency direction stays clean: features depend on shared types, never on each other's internals.
Set compiler guardrails early: strict: true from day one, no-floating-promises and no-explicit-any lint rules, and consistent path aliases. Retrofitting strictness onto a mature codebase costs weeks; starting strict costs nothing.
// A feature-first layout:
//
// src/
// shared/
// types/ <- cross-cutting domain types, API contracts
// lib/ <- fetch wrapper, result helpers
// features/
// billing/
// api.ts <- typed endpoint calls
// service.ts <- business logic
// types.ts <- billing-only types
// accounts/
// ...
// app/ <- composition: routing, DI, bootstrap
//
// Rule: features import from shared/, never from each other.Feature folders localize change; shared types define the contract layer.
Typing API Boundaries Honestly
The network is where type safety goes to die: response.json() returns any (or unknown at best), and a cast to your expected type is a hope, not a check. The honest pattern is to treat every external payload as unknown and validate it at the boundary — with hand-written type guards or a schema library like zod, where the schema is the single source of truth and the static type is derived from it.
Once validated, data flows through the app with full type safety and zero further checks. This 'validate once at the edge, trust inside' architecture concentrates all defensive code in one thin layer instead of smearing null checks through the business logic.
Model failures in the types too. A fetch wrapper returning Result<User, ApiError> — a discriminated union of success and failure — forces callers to handle errors where a thrown exception lets them forget. Reserve exceptions for bugs; expected failures (404s, validation errors) deserve a place in the return type.
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
interface ApiUser {
id: number;
email: string;
}
function parseUser(data: unknown): Result<ApiUser, string> {
if (
typeof data === "object" &&
data !== null &&
"id" in data &&
typeof (data as { id: unknown }).id === "number" &&
"email" in data &&
typeof (data as { email: unknown }).email === "string"
) {
return { ok: true, value: data as ApiUser };
}
return { ok: false, error: "Payload does not match ApiUser" };
}
const result = parseUser(JSON.parse('{"id":1,"email":"a@b.co"}'));
if (result.ok) {
console.log(result.value.email); // fully typed from here on
}Validate once at the edge; everything inside is trustworthy.
Sharing Types Across Frontend and Backend
When the server and client define request/response shapes separately, they drift — and drift ships as production bugs the compiler was never allowed to see. The cure is a single definition both sides import: a shared package in a monorepo, generated types from an OpenAPI spec, or end-to-end inference with tools like tRPC.
Keep the shared layer to contracts: request bodies, response shapes, enums, error codes. Do not leak server internals (database entities, ORM classes) to the client — map them into API types at the boundary, both to decouple deploys and to avoid accidentally shipping fields like passwordHash to a browser bundle.
Contracts also need versioning discipline. Additive changes (new optional fields) are safe; renames and removals break clients. Making old fields optional-but-deprecated in the shared type, with a comment pointing at the replacement, lets the compiler walk every consumer through a migration.
// shared/types/api.ts — imported by BOTH server and client.
export interface CreateOrderRequest {
items: Array<{ sku: string; qty: number }>;
couponCode?: string;
}
export interface CreateOrderResponse {
orderId: string;
total: number;
estimatedDelivery: string; // ISO date — Date does not survive JSON!
}
export type ApiErrorCode =
| "invalid_coupon"
| "out_of_stock"
| "payment_failed";
// Server: implements the contract. Client: consumes it.
// One definition, zero drift.The contract lives in one place; both sides submit to it.
JSON's Sharp Edges
JSON has fewer types than TypeScript, and the difference bites at every boundary. Date survives serialization only as a string; undefined properties vanish entirely; Map, Set, and bigint do not serialize at all. Your API types must reflect the wire format — createdAt: string — not the in-memory ideal.
The vanishing-undefined behavior interacts with exactOptionalPropertyTypes: a property you set to undefined disappears from the JSON, so the receiving side sees an absent key. If 'explicitly cleared' and 'not provided' mean different things in your API (PATCH semantics!), you need null for clearing, not undefined.
Handle the string-to-rich-type conversion in one mapping layer: a fromApi function per resource that parses dates and normalizes shapes. Sprinkling new Date(x) throughout components guarantees someone eventually forgets, and a string masquerading as a Date fails in the strangest ways.
interface OrderDto {
id: string;
createdAt: string; // wire format: ISO string
}
interface Order {
id: string;
createdAt: Date; // app format: real Date
}
function fromApi(dto: OrderDto): Order {
return {
id: dto.id,
createdAt: new Date(dto.createdAt),
};
}
const wire = JSON.stringify({ id: "o1", createdAt: new Date().toISOString() });
const order = fromApi(JSON.parse(wire) as OrderDto);
console.log(order.createdAt instanceof Date); // true — converted exactly onceDTO types mirror the wire; one mapper upgrades them to app types.
Testing in a Typed Codebase
Types change what deserves a test. You no longer test that a function rejects a string where a number belongs — the compiler proves that. Spend the test budget on behavior: business rules, edge values, error paths, and integration seams where types cannot reach (real HTTP, real database, real clock).
Keep test data honest with typed factory functions: makeUser(overrides?: Partial<User>) returns a valid User with sensible defaults and typo-proof overrides. When the User type gains a required field, every factory fails to compile — a to-do list for updating tests, delivered by the compiler.
Types themselves can be tested. A helper like expectType<T>(value: T) — or the expect-type library — turns 'this should infer as string' into a compile-checked assertion, which matters for library authors whose public API is the types. And resist as any in tests: a test that lies to the compiler about its inputs tests a scenario production can never produce.
interface User {
id: number;
name: string;
role: "viewer" | "admin";
}
// Typed factory: defaults + safe overrides.
function makeUser(overrides: Partial<User> = {}): User {
return { id: 1, name: "Test User", role: "viewer", ...overrides };
}
function canDelete(user: User): boolean {
return user.role === "admin";
}
// The tests read as specifications:
console.log(canDelete(makeUser()) === false);
console.log(canDelete(makeUser({ role: "admin" })) === true);
// Compile-time assertion helper:
function expectType<T>(_value: T): void {}
expectType<boolean>(canDelete(makeUser()));Factories keep test data valid; the compiler maintains them for you.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
Why is 'validate at the boundary, trust inside' preferred over checking data shapes throughout the codebase?
Question 2 · Predict the output
What does this program print?
const order = {
id: "o1",
createdAt: new Date("2026-01-15T00:00:00Z"),
};
const wire = JSON.stringify(order);
const revived = JSON.parse(wire) as typeof order;
console.log(revived.createdAt instanceof Date, typeof revived.createdAt);Question 3 · Find the error
This shared API type causes a security review finding. What is the problem?
// shared/types/api.ts — imported by client AND server
export interface UserResponse {
id: number;
email: string;
passwordHash: string;
failedLoginAttempts: number;
}Question 4 · True or false
In a well-typed codebase, unit tests verifying that functions reject arguments of the wrong type are largely redundant.
Question 5 · Multiple choice