Hand-writing a TypeScript interface or a Python class for every API response is tedious and goes stale the moment the payload changes. A faster start is to generate the types directly from a sample of the JSON, then refine the parts a single sample cannot know. This guide shows how to do that for TypeScript and Python, what the generators get wrong, and when to switch to a schema-first approach instead.
If you are new to the format, skim what JSON is first; this guide assumes you know objects, arrays and the six value types.
Why generate types at all?
Types are documentation the compiler checks. When your code says a response has { id: number; name: string }, the editor autocompletes those fields and flags a typo before you run anything. The problem is drift: APIs add and rename fields, and hand-maintained types quietly fall out of sync. Generating them from a real payload keeps the shape honest and saves the busywork of transcribing a large object by hand.
TypeScript from a JSON sample
Paste a representative response into the JSON to TypeScript tool and it produces an interface per object shape, nesting them as needed:
interface User {
id: number;
name: string;
roles: string[];
profile: Profile;
}
interface Profile {
city: string;
joined: string; // ISO date as a string
}
Notice joined is typed string: JSON has no date type, so a date arrives as text and the generator can only see a string. That is the first thing to refine by hand.
The fields a single sample gets wrong
A generator infers from exactly one example, so it cannot see three things you must fix yourself:
- Optional fields. A key present in your sample is typed as required. If the API sometimes omits it, mark it optional:
middleName?: string. - Nullable fields. A value that was non-null in the sample hides the fact it can be
null. Widen it:deletedAt: string | null. - Unions and enums. A
statusthat reads"open"becomesstring, losing the fact it is really"open" | "closed" | "archived".
Feed the generator a sample that includes nulls and the less common variants, and you will get closer on the first pass.
Python models from JSON
The workflow is identical for Python. The JSON to Python tool emits dataclasses (or TypedDict) from a sample:
from dataclasses import dataclass
from typing import Optional
@dataclass
class Profile:
city: str
joined: str
@dataclass
class User:
id: int
name: str
roles: list[str]
profile: Profile
middle_name: Optional[str] = None # refined by hand
As with TypeScript, the generated classes are a starting point — add Optional[...] for fields that can be missing or null, and consider a validation library if the data is untrusted.
The schema-first alternative
Generating from one sample is fast but guesses. When correctness matters — a public API, a payment payload — generate from a JSON Schema instead. A schema states exactly which fields are required, which are nullable, and what values an enum allows, so the generated types are accurate rather than inferred. The schema also doubles as runtime validation, which types alone do not provide: TypeScript types vanish at compile time and Python hints are advisory. For a robust pipeline, keep a schema as the source of truth and generate both the validator and the types from it. The same idea powers server-side generators like our guide on building a Laravel model and migration from JSON.
A practical workflow
Put it together: capture a real response and format it so you can read the structure; generate a first draft of the types with the converter; refine optional, nullable and union fields by hand; and, if the data is untrusted or the contract is important, back the types with a JSON Schema for runtime validation. That sequence gives you accurate types in minutes instead of transcribing a payload by hand and missing half the edge cases.
Keeping generated types in sync
Generation is not a one-off. The whole point is that the payload changes over time, so the types must regenerate when it does. Two patterns keep them honest. The first is to treat the types as build output: check a representative sample fixture into the repo, regenerate the types from it in a script, and fail the build if the committed types drift from what the sample produces. The second is to generate from the API's published schema rather than a captured sample, so a change to the contract flows straight into the types. Either way, resist editing generated files so heavily that you cannot regenerate them — keep your hand-refinements small and mechanical (adding ? and | null), or move to a schema so the generator produces them for you.
Arrays of mixed or inconsistent shapes
Generators assume an array is homogeneous — every element the same shape — and type it from the first element. Real data is not always so tidy. If an array mixes shapes, or objects in a list have different optional fields, the generated element type will be too narrow. Feed the tool a sample that includes the variations, then widen the element type to a union if the shapes are genuinely different. When a list is really a tagged union (each item has a type field that decides its other fields), model it as a discriminated union in TypeScript so the compiler narrows correctly — something no single sample can infer for you.
Tools that do this
Beyond the built-in converters, dedicated generators like quicktype, json2ts and json-to-ts are popular because they handle many languages from one input and offer options for naming, optionality and whether to emit runtime validators alongside the types. Whichever you use, the discipline is the same: generate from a representative sample, review the optional and nullable fields, and prefer a schema as the source once the shape stabilises. The tool saves the typing; you still own the correctness.
Key takeaways
- Generate a first draft of types from a JSON sample, then refine it.
- A single sample cannot see optional, nullable or union fields — fix those by hand.
- Dates are strings in JSON, so generated date fields need widening.
- Generate from a JSON Schema when accuracy and runtime validation matter.
- Types document and check at build time; they do not validate data at runtime.