Testing & Code Quality

Type-Safe API Boundaries

TypeScript is strongest inside your codebase. Boundaries such as JSON, forms, URL params, localStorage, environment variables, and third-party libraries are unknown runtime data until validated.
  • Boundary data should start as unknown
  • Validation should happen once at the edge
  • Wrappers contain unsafe interop
  • Boundary tests are high value
  • Types and schemas can drift
Safe boundary flow
The unsafe value crosses the boundary once.
Unknown JSON boundary
async function getJson(url: string): Promise<unknown> {
  const res = await fetch(url)
  if (!res.ok) throw new Error(`HTTP ${res.status}`)
  return res.json()
}

const raw = await getJson("/api/user/u1")
const user = parseUser(raw)
// user is now trusted User inside the app.
Avoid returning `Promise<User>` directly from unvalidated JSON parsing.
Boundary protections
BoundaryRiskProtection
HTTP JSONShape changed or invalidSchema/parser
Form inputStrings and missing fieldsField validation
URL paramsEverything is stringParse + validate
localStorageStale/manual dataParser + fallback
env varsMissing/malformed configStartup validation
Untyped dependencyany spreadSmall typed wrapper
Sources
  • Effective TypeScript, 2nd EditionType-safe boundaries
  • The TypeScript Handbookunknown and narrowing
  • Vitest DocumentationTesting