PureTools

JSON to TypeScript: Generate Types from API Responses

PureTools Team· 5 min read
JSON to TypeScript: Generate Types from API Responses

JSON to TypeScript: Type Your APIs in Seconds

You hit an API, get a JSON response, and now you need TypeScript types for it. You can spend 10 minutes hand-writing interfaces, or you can paste the JSON and get types instantly.

The Manual Way (Slow)

// API returns:
{
  "id": 42,
  "name": "Alice",
  "email": "alice@example.com",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "zip": "62701"
  },
  "tags": ["admin", "verified"],
  "createdAt": "2024-01-15T10:30:00Z"
}

// You write:
interface Address {
  street: string;
  city: string;
  zip: string;
}

interface User {
  id: number;
  name: string;
  email: string;
  address: Address;
  tags: string[];
  createdAt: string;
}

The Fast Way

Paste the JSON into a converter tool and get the TypeScript interfaces generated automatically. It handles nested objects, arrays, optional fields, and union types.

Edge Cases the Tool Handles

JSON ValueGenerated Type
42number
"hello"string
trueboolean
nullnull (or type | null)
[1, "two"](number | string)[]
{...}Nested interface
[{...}, {...}]Interface[] (merged from all items)

Tips for Better Types

  • Use multiple response examples — a single response might not show optional fields. Test with different data to catch nullable fields.
  • Rename generated names — tools generate names like RootObject. Rename to User, Product, etc.
  • Add strict types — replace string with unions where appropriate: status: 'active' | 'inactive' instead of status: string.
  • Use readonly for API responses — data from APIs shouldn't be mutated.
// After conversion, refine:
interface User {
  readonly id: number;
  readonly name: string;
  readonly email: string;
  readonly role: 'admin' | 'user' | 'guest';  // refined from string
  readonly address: Readonly<Address>;
  readonly tags: readonly string[];
  readonly createdAt: string;  // or Date if you parse it
}

Programmatic Conversion

// quicktype — CLI tool
npx quicktype --src data.json --lang ts --just-types

// json-to-ts — npm package
import JsonToTS from 'json-to-ts';
const types = JsonToTS({ name: 'Alice', age: 30 });
// ['interface RootObject { name: string; age: number; }']

Generate your types: JSON to TypeScript — paste any JSON, get clean TypeScript interfaces instantly.