Dev Basics · 5 min read
Typing API Responses: From JSON to TypeScript Types
An untyped API response is the most common hole in a TypeScript codebase: const data = await res.json() is any, and everything after it is unchecked. Generating types from real JSON closes that hole quickly.
Try it yourself with the related tool.
Generate types from JSON →Advertisement
From sample to interface
A generator walks a JSON sample and maps each value to a type: strings to string, numbers to number, nested objects to their own interfaces, and arrays to Item[]. The output is a starting point you then name and tidy up — for example renaming Root to User.
Optional vs nullable
One sample cannot tell you which fields are sometimes missing. A key that is absent in some responses should be optional — nickname?: string — while a key that is present but empty should be nickname: string | null. Feeding several samples to a generator lets it compare them and infer both correctly.
Watch for lossy guesses
Dates arrive as strings, so they become string, not Date. An empty array becomes unknown[] or any[] — fill it in by hand. A field that is always "active" in the sample is probably a union like "active" | "disabled". And very large IDs may exceed JavaScript's safe integer range; treat them as strings.
Types are not validation
TypeScript types disappear at runtime, so they cannot stop a changed API from breaking your app. A schema library such as Zod checks the data when it arrives and infers the TypeScript type from the same schema with z.infer, so the type and the check never drift apart. Validate at the boundary — where data enters your app — and trust the types after that.
