How to Generate TypeScript Types from JSON
Typing an API response by hand is slow and easy to get wrong, especially when the payload is large or deeply nested. A faster path is to take a real JSON sample and generate the TypeScript interfaces from it. This guide explains how that inference works, how arrays and optional fields are handled, and how to turn the generated output into types you'd be happy to ship.
Why type your JSON?
TypeScript types turn a runtime surprise into a compile-time error. Once an API response is described by an interface, your editor autocompletes its fields, the compiler catches typos and wrong assumptions, and refactors become safe. The only friction is writing the types in the first place — which is exactly what generating them from a sample removes.
From a JSON sample to interfaces
The idea is simple: paste a representative JSON object and get back a set of named interfaces. A flat object like one with a numeric id and a string name becomes an interface with id: number and name: string. Each nested object is promoted to its own named interface — a maintainer object becomes a Maintainer interface that the parent references — so the result is clean and reusable instead of one giant inline type.
How types are inferred
Each value maps to the natural TypeScript type:
- Strings, numbers, and booleans map to string, number, and boolean.
- Objects become named interfaces, named after the key that holds them.
- Arrays become T[], where T is inferred from the elements.
- An array of objects is merged into one interface covering every element.
- Mixed scalar arrays become a union, such as (string | number)[].
Handling tricky shapes
Real data is rarely uniform, and a good generator handles the rough edges. When an array of objects has a key that's present in some elements but not others, that key is marked optional with a ? so the type stays accurate. A null value is typed as null on its own — worth widening by hand to something like string | null if the field is genuinely nullable. Empty arrays become unknown[], since there's nothing to infer an element type from.
Tips for production-ready types
Generation gets you ninety percent of the way; a few touch-ups finish the job. Rename the root interface from the default to your domain name. Feed the generator the most complete sample you have — including the fields that are sometimes absent — so optional keys are detected correctly. And review nullable fields, since a single sample can only show the value it happens to contain.
Try it yourself
Turn a JSON sample into clean, ready-to-use TypeScript interfaces in one click.