JSON to TypeScript: Stop Hand-Writing Interface Definitions

2024-08-04

Hand-written interfaces drift from real API responses. Generating TypeScript types from sample JSON is standard—if you understand the rules and limits.

Why generate types?

Catch typos and null access at compile time; use real payloads when OpenAPI is missing or stale.

Manual mapping example

JSON
{ "id": 1, "name": "Alice", "email": null }
TypeScript
interface User {
  id: number;
  name: string;
  email: string | null;
}

Nested arrays and unions

Empty arrays need a manual element type; heterogeneous arrays become unions.

Optional vs null

Missing keys (email?) differ from null values (email: string | null)—align with backend semantics.

Tools

quicktype CLI, json-schema-to-typescript, online json2ts for one-offs.

# npx quicktype sample.json -o types.ts --lang typescript

Best practices

Regenerate instead of editing generated files; use multiple samples; let tsc surface breaking API changes.