DEV Community

arenasbob2024-cell
arenasbob2024-cell

Posted on • Originally published at viadreams.cc

JSON to TypeScript: Generate Types Automatically in 2026

Working with JSON APIs in TypeScript? Generating types from JSON data saves hours and prevents bugs.

Why Generate Types?

Without types:

const data = await fetch('/api/users').then(r => r.json());
console.log(data.name); // No autocomplete, no type checking
Enter fullscreen mode Exit fullscreen mode

With generated types:

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

const data: User = await fetch('/api/users').then(r => r.json());
console.log(data.name); // Full autocomplete + type checking
Enter fullscreen mode Exit fullscreen mode

interface vs type

// interface - extendable, better for objects
interface User {
  id: number;
  name: string;
}

// type - better for unions, intersections
type Status = 'active' | 'inactive';
type UserWithStatus = User & { status: Status };
Enter fullscreen mode Exit fullscreen mode

Handling Optional Fields

interface ApiResponse {
  id: number;
  name: string;
  email?: string;        // Optional
  avatar: string | null;  // Nullable
}
Enter fullscreen mode Exit fullscreen mode

Runtime Validation with Zod

import { z } from 'zod';

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email().optional(),
  roles: z.array(z.string()),
});

type User = z.infer<typeof UserSchema>;

// Validates at runtime!
const user = UserSchema.parse(apiResponse);
Enter fullscreen mode Exit fullscreen mode

Generic API Response Type

interface ApiResponse<T> {
  data: T;
  meta: { page: number; total: number };
  error?: string;
}

type UsersResponse = ApiResponse<User[]>;
Enter fullscreen mode Exit fullscreen mode

Try It Online

Generate TypeScript types from JSON with DevToolBox JSON to TypeScript - handles nested objects, arrays, optionals.


interface or type alias? Share your preference!

Top comments (0)