jsontypescriptinterfacesapi

JSON to TypeScript: Auto-generate Interfaces

·5 min read

Why Generate TypeScript Interfaces from JSON?

When you integrate a REST API, you typically receive JSON responses. Writing TypeScript interfaces by hand for every endpoint is tedious, error-prone and gets out of sync as APIs change. An automatic generator reads the actual JSON and produces accurate interfaces in seconds.

How the Generator Works

1. Parse the JSON value 2. Infer the TypeScript type for each key 3. Recursively handle nested objects — each gets its own named interface 4. Handle arrays — inspect the first element to determine the element type 5. Output interfaces in order: parent first, children after

Generated Output Example

Input JSON:

json
{
  "user": {
    "id": 1,
    "name": "Ravi Mehta",
    "roles": ["admin", "editor"],
    "address": {
      "city": "Surat",
      "pincode": "395001"
    }
  }
}

Generated TypeScript:

typescript
interface Root {
  user: User;
}

interface User {
  id: number;
  name: string;
  roles: string[];
  address: Address;
}

interface Address {
  city: string;
  pincode: string;
}

Type Mapping Rules

| JSON value | TypeScript type | |---|---| | "hello" | string | | 42, 3.14 | number | | true / false | boolean | | null | null | | [] | unknown[] (if empty) | | ["a", "b"] | string[] | | [1, "x"] | (number | string)[] | | {} | named interface |

Handling Optional Fields

If a field appears as null in your sample JSON, the generator types it as `field: null`. In practice, you may want to widen it to `field: string | null` after generation. Always check the generated interfaces against the full API contract, not just a single sample response.

Best Practices

  • Use the actual API response as input, not a hand-crafted example
  • Generate interfaces after every API contract change
  • Add the interfaces to a dedicated `types/api.ts` file
  • Use the interfaces with `fetch` and generic type parameters:
typescript
const data = await fetch("/api/user").then(r => r.json()) as Root;
console.log(data.user.name); // typed!

Use JSONKit's JSON to TypeScript tool to generate interfaces instantly from any JSON — paste, convert, copy, done.

Try JSON to TypeScript

Generate TypeScript interfaces from any JSON object automatically.