JSON to TypeScript: Generate Types Automatically

August 1, 20269 min read

Working with JSON API responses in TypeScript without proper types means losing IDE autocomplete, missing type errors at compile time, and spending hours debugging runtime issues that TypeScript would have caught immediately. Generating TypeScript types from your JSON is one of the highest-value activities you can do when starting to work with a new API.

This guide covers how to generate TypeScript interfaces from JSON automatically, how to write them manually for complex cases, and how to get runtime validation alongside compile-time types using Zod.

Why TypeScript Types for JSON?

Generate TypeScript Interfaces from JSON with IRJSON

IRJSON's converter generates TypeScript interfaces from any JSON document with one click. Paste your JSON, click TypeScript, and get interfaces ready to copy into your project:

What the Generated TypeScript Looks Like

Given this JSON API response:

{
  "user": {
    "id": 42,
    "name": "Alice Nguyen",
    "email": "alice@example.com",
    "roles": ["admin", "editor"],
    "profile": {
      "avatarUrl": "https://cdn.example.com/alice.jpg",
      "joinedAt": "2024-03-15T10:30:00Z"
    }
  }
}

IRJSON generates:

interface Profile {
  avatarUrl: string
  joinedAt: string
}

interface User {
  id: number
  name: string
  email: string
  roles: string[]
  profile: Profile
}

interface Root {
  user: User
}

interface vs type Alias

TypeScript gives you two ways to define object shapes:

// Interface — can be extended and implemented
interface User {
  id: number
  name: string
}

interface AdminUser extends User {
  adminKey: string
}

// Type alias — more flexible, supports unions and intersections
type User = {
  id: number
  name: string
}

type AdminUser = User & { adminKey: string }

// Union types require type alias
type Status = 'active' | 'inactive' | 'pending'

// Record type for dynamic keys
type TagMap = Record<string, string[]>

For plain JSON shapes that match a fixed structure, interface is the conventional choice. When you need union types, mapped types or conditional types, use type.

Handling Optional vs Required Fields

JSON often has optional fields — properties that may or may not be present. Mark them with ? in TypeScript:

interface User {
  id: number
  name: string
  email: string
  avatarUrl?: string   // optional — may be absent
  phone?: string | null  // optional and nullable
}

When generating types automatically, IRJSON marks fields as optional if they are absent in any of the sample records.

Arrays and Union Types

// Array of objects
interface Order {
  id: string
  items: OrderItem[]   // array of typed objects
  total: number
}

interface OrderItem {
  productId: string
  quantity: number
  price: number
}

// Nullable field — union with null
interface Product {
  id: number
  description: string | null   // can be string or null
  discount?: number | null     // optional and nullable
}

Runtime Validation with Zod

TypeScript types only exist at compile time — they are erased when compiled to JavaScript. At runtime, you have no guarantee that the API actually returns the shape you typed. Zod solves this by providing runtime validation that also infers TypeScript types:

import { z } from 'zod'

const UserSchema = z.object({
  id: z.number().int().positive(),
  name: z.string().min(1),
  email: z.string().email(),
  roles: z.array(z.enum(['admin', 'editor', 'viewer'])),
  avatarUrl: z.string().url().optional(),
})

// Infer the TypeScript type from the schema
type User = z.infer<typeof UserSchema>

// Parse and validate at runtime
const response = await fetch('/api/user/42')
const data = await response.json()

const result = UserSchema.safeParse(data)
if (!result.success) {
  console.error('API response validation failed:', result.error.issues)
} else {
  const user = result.data  // TypeScript knows this is User
  console.log(user.name)
}

Generic Utility Types for JSON

// Make all properties optional
type PartialUser = Partial<User>

// Make all properties required
type RequiredUser = Required<User>

// Pick specific fields
type UserSummary = Pick<User, 'id' | 'name' | 'email'>

// Omit specific fields
type PublicUser = Omit<User, 'adminKey' | 'internalId'>

// Map over keys with transformation
type ReadonlyUser = Readonly<User>

Frequently Asked Questions

Should I use interface or type for JSON types?

Both work well for JSON shapes. Use interface when you expect to extend or implement the type. Use type alias when you need union types, intersections or mapped types. For pure JSON data shapes from APIs, interface is the conventional choice and is slightly more performant in the TypeScript compiler for large codebases.

Can I generate Zod schemas from JSON?

Yes. IRJSON's converter can generate Zod schema definitions in addition to TypeScript interfaces. Zod gives you both runtime validation and inferred TypeScript types from a single schema definition — the best of both worlds.

What about Pydantic for Python?

IRJSON's converter also generates Python Pydantic v2 model classes from JSON. Pydantic v2 provides runtime validation and IDE type hints. It is the standard for FastAPI models and increasingly common across all Python projects that deal with JSON.

Generate TypeScript types from JSON free

IRJSON converts JSON to TypeScript interfaces, Zod schemas and Pydantic models instantly in your browser.

Open Converter →