TypeScript

Type-Safe APIs at Scale

Type safety across a network boundary is one of those things that's trivially achievable on day one and agonizingly hard to retrofit on day five hundred. The hard part isn't picking a tool - it's keeping the contract, the client, and the server in lockstep as teams, services, and versions multiply.

API architecture diagram

Pick a Source of Truth, Then Commit

Every type-safe API stack fails the same way: two sources of truth drift apart. The schema lives in one place, the handwritten client lives in another, and the runtime validator lives in a third. Pick one authoritative representation and generate everything else from it.

  1. tRPC - the source is your TypeScript router. Best when both ends are TS and you control both. Zero codegen, zero schema files, but also zero story for non-TS clients.
  2. GraphQL with codegen - the source is the SDL. Great for fan-out to mobile and partner clients. Pay for it in tooling complexity and resolver discipline.
  3. OpenAPI with generated clients - the source is the spec. Lingua franca across languages. Requires you to actually treat the spec as the contract, not as documentation written after the fact.

Runtime Validation Is Not Optional

TypeScript types evaporate at the network edge. If you aren't validating incoming payloads with Zod, Valibot, or an OpenAPI-derived validator, your "type-safe" API is a suggestion. The rule of thumb: parse at the boundary, trust internally, and let the parser's output type be the one your code consumes. Never cast.

Versioning Without Breaking Clients

Breaking changes are inevitable. The trick is making them cheap:

  • Add fields freely; remove them slowly, behind a deprecation window.
  • Version at the operation level where possible (createUser.v2) rather than the whole API - it lets you migrate piecemeal.
  • Keep a changelog generated from the schema diff. "We forgot to tell mobile" is the most expensive bug in any org.

The right stack depends on who your clients are and how much language diversity you're supporting. The discipline doesn't: one source of truth, runtime validation at the edges, and a humane story for change over time.

TypeScriptArchitecture

Lovro Hudrap

TypeScript

Writing about typescript and the craft of building for the web.