Skip to content

Lesson 3 of 9 · 25m

Type-Safe Boundaries: APIs, Events, and Storage

Using generics and discriminated unions at system boundaries so malformed payloads, mismatched event names, and stale stored data fail early and loudly.

The highest-value typing work is not inside a clever utility type; it is at boundaries. Every request body, websocket event, queue message, environment variable, and row read from Postgres is a place where reality can disagree with your assumptions. Advanced types pay rent when they preserve the shape of that boundary all the way through the application.

Tie request and response types together

type Endpoint<Req, Res> = {
  method: "GET" | "POST"; path: string;
  parse: (input: unknown) => Req; respond: (request: Req) => Promise<Res>;
};

const createInvoice: Endpoint<
  { customerId: string; amountCents: number }, { id: string; status: "open" | "paid" }
> = {
  method: "POST", path: "/api/invoices", parse: validateCreateInvoice, respond: invoiceService.create,
};

Now the client, handler, validator, and tests all orbit the same contract. The generic relationship is the architecture.

Discriminated unions beat stringly typed events

type DomainEvent =
  | { type: "invoice.created"; invoiceId: string; amountCents: number }
  | { type: "invoice.paid"; invoiceId: string; paidAt: string }
  | { type: "customer.deleted"; customerId: string };

function publish<T extends DomainEvent["type"]>(type: T, payload: Omit<Extract<DomainEvent, { type: T }>, "type">) {
  bus.emit(type, payload);
}

publish("invoice.paid", { invoiceId: "inv_1042", paidAt: new Date().toISOString() });

Extract connects the event name to the payload. If a producer forgets paidAt, the compiler catches it before a consumer crashes at midnight.

Validate at the edge, refine inward

TypeScript cannot validate runtime input. Libraries like zod solve the other half: parsing unknown data and producing a typed value.

const Env = z.object({
  DATABASE_URL: z.string().url(),
  STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
  PORT: z.coerce.number().int().min(1).max(65535),
});

const env = Env.parse(process.env);

The rule is simple: accept unknown, parse once, then pass typed values inward. Do not sprinkle as through the middle of the system.

Field notes

  • any at a boundary spreads silently; unknown forces validation and is almost always what you meant.
  • Persisted data is a versioned boundary. Decode old shapes deliberately instead of pretending migrations happen by magic.
  • Use satisfies to check an object against a contract without widening away its literal details.
  • Type errors at boundaries are design feedback. If the compiler complains everywhere, the contract may be wrong — not merely the annotations.

Was this lesson helpful?

Sign in to rate