JSON to TypeScript
Turn a real API response into TypeScript interfaces, with nested types and optional fields inferred.
From a real payload to a real type
Hand-writing interfaces from an API response is slow and error-prone: field names get mistyped, nested objects get flattened, and nullable fields are forgotten until production. Generating the skeleton from an actual response gives you a type that is guaranteed to match the data you are looking at — then you tighten it.
What the generator infers
- Primitives map to
string,numberandboolean. JSON has one numeric type, so integers and floats both becomenumber. - Nested objects become their own exported interface, named after the key that contains them (
profile→Profile). - Arrays of objects are merged: if one element has an extra key, the resulting interface includes it. Fields missing from some elements are the place to add
?by hand. nullbecomes the literal typenull, which is a signal to widen the field to a union such asstring | null.- Empty arrays become
unknown[]— the generator refuses to guess.
What it cannot know
A sample is a single observation. Optional fields, unions of string literals, date strings, and enums all look like plain values. The honest workflow is: generate, then review each field and tighten it. In particular:
- A field that is always present in the sample may be absent in production → make it optional.
"2024-01-31T10:00:00Z"is astring, but you probably want a branded date type or a parsedDate.- Status codes like
"active" | "paused"infer asstring; replace with the real union.
Run the type check against the API, not against your memory
The most reliable habit is to keep one captured response as a fixture and assert that it satisfies the generated type in a test (expectTypeOf<typeof fixture>().toMatchTypeOf<User>()). When the API changes, the test fails before your users find out. Tools like Zod or Valibot take this further: define the schema once, derive the TypeScript type and validate at runtime.
Frequently asked questions
Should I use interfaces or type aliases?
Why are some fields marked with null?
null. Widen it manually to string | null (or add ? if the key can be missing entirely) — TypeScript treats those as different things.