Guide · 6 min read
Generate TypeScript types from JSON that tell the truth
The JSON to TypeScript step usually starts by copying an API response into an editor and hand-writing an interface — a small task that hides a large risk: the types you write describe the one response you saw, not the responses your users will trigger.
Updated
JSON to TypeScript: start from a representative payload, not a lucky one
A generator can only infer what your sample shows. Fetch a response that includes the awkward cases: a record with the optional field present and one without, a null, an empty array, a decimal. One good sample beats five clean ones.
Optional fields come from arrays
Given a single object, every key looks required. Given an array of objects, a generator can compare items: a key missing from some items is optional (key?: string), and a key present everywhere is required. This is why pasting a list of records produces dramatically better types than pasting one record.
Model nulls honestly
// One sample with "deleted_at": null and one with a date
interface User {
id: number;
deleted_at: string | null; // not string, not optional
}
null and undefined are different things. A nullable field is present with a null value; an optional field may be absent entirely. Generators that collapse the two produce interfaces that type-check while being wrong — the most expensive kind of wrong, because the compiler stops warning you.
Unions beat any
When a field is a string in one record and a number in another — messy APIs exist — the honest type is string | number. Falling back to any or unknown silences the compiler and pushes the failure to production. A generator that reports the union at least documents the reality, and you can then ask the API team why.
Types are compile-time; validate at runtime
- TypeScript disappears at runtime. Nothing stops a malformed payload from arriving with a shape your interface forbids.
- Use generated types to describe what you expect, and a runtime validator (Zod, Valibot, or a JSON Schema with AJV) at the boundary where data enters your app.
- Generating a JSON Schema from the same sample gives you the runtime half — the schema validates, the interfaces document.
Keep types regenerated, not retyped
Types written by hand drift from the API. Treat the generator as a step in your workflow: paste a fresh response, regenerate, paste into your types file, and let the compiler show you every place the API changed. It is the cheapest API-drift detector there is — and it costs thirty seconds.
Try it with the JSON to TypeScript generator — interface or type output, optional keys detected, unions preserved.