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
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
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 };
Handling Optional Fields
interface ApiResponse {
id: number;
name: string;
email?: string; // Optional
avatar: string | null; // Nullable
}
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);
Generic API Response Type
interface ApiResponse<T> {
data: T;
meta: { page: number; total: number };
error?: string;
}
type UsersResponse = ApiResponse<User[]>;
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)