Back to blog

TypeScript patterns for safer APIs

Practical ideas for narrowing types at boundaries and catching mistakes before production.

TypeScript patterns for safer APIs

Modern TypeScript shines when you treat types as documentation that the compiler enforces. At module boundaries—HTTP handlers, database rows, third-party JSON—use explicit types or validation instead of any.

Narrow early

Parse unknown input once, then work with a known shape. Libraries like Zod pair well with TypeScript: you get runtime checks and inferred static types from the same schema.

Prefer unions over strings

Replace open-ended string with as const arrays or string unions when the set of values is fixed. Your editor autocomplete improves, and impossible states become compile-time errors.

Summary

Small habits—validation at the edge, precise unions, and avoiding any—pay off as the codebase grows. The goal is not perfection; it is failing fast where mistakes are cheapest.