How to Generate TypeScript Interfaces from JSON
When you're consuming an API, hand-writing TypeScript types for its responses is tedious and error-prone. Generating them from a real JSON sample is faster and more accurate. Here's how the inference works and where to double-check it.
From JSON to interfaces
Given a JSON object, each field maps to a typed property, and each nested object becomes its own named interface:
{ "id": 1, "name": "Ada", "address": { "city": "London" } }
export interface Root {
id: number;
name: string;
address: Address;
}
export interface Address {
city: string;
}
Separate interfaces (instead of one deeply inline type) keep the result reusable and readable.
Arrays, optional fields, and unions
Arrays of objects are the interesting case. A good generator merges every object in the array so the type reflects all of them:
- A key present in only some elements becomes optional (
name?: string). - A key whose value type differs across elements becomes a union (
id: number | string).
Arrays of primitives become string[], number[], and so on.
What to check afterward
Inference from a single sample has limits — review these:
nullfields. If a sample value isnull, its real type is unknown, so it's typed asnull. Replace it with the correct type.- Empty arrays become
any[]— there's nothing to infer from. - Optional vs nullable. A field the API sometimes omits is different from one it sends as
null; adjust to match the actual contract.
Treat the output as a strong first draft you refine, not a schema.
Related
Working with the same JSON in other shapes? See JSON to YAML and the Complete Guide to JSON.
Try it
Paste a JSON response and get TypeScript interfaces instantly — everything runs in your browser, nothing uploaded.