TypeScript Interfaces from JSON – Complete Guide
Learn how to generate TypeScript interfaces from JSON data. Understand interface syntax, optional properties, union types, nested types, and best practices for type-safe development.
What Are TypeScript Interfaces?
A TypeScript interface defines the shape of an object — what properties it has, what types those properties are, and which ones are optional. Interfaces are a cornerstone of TypeScript's type system and are essential for writing type-safe code.
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
Why Generate Interfaces from JSON?
When you work with REST APIs, GraphQL responses, or configuration files, the data arrives as JSON. Manually writing interfaces is tedious and error-prone. Generating them from actual JSON payloads ensures:
- Accuracy: Types match the real data structure
- Speed: Seconds instead of minutes for complex objects
- Consistency: No human typos or missed fields
Interface Syntax Basics
Required Properties
By default, all properties in an interface are required:
interface Product {
id: number;
name: string;
price: number;
}
Optional Properties
Properties that may or may not be present use the ? modifier:
interface Product {
id: number;
name: string;
price: number;
description?: string; // may be absent
discount?: number; // may be absent
}
Our converter marks a property as optional when its value is null in the JSON input, since null indicates the field might not always have a value.
Union Types
When a property can hold different types, TypeScript uses union types:
interface ApiResponse {
data: string | number; // could be either
error?: string | null; // optional, could be null
}
Nested Objects
When JSON contains nested objects, each level gets its own interface:
{
"user": {
"name": "Alice",
"address": {
"city": "Portland",
"zip": "97201"
}
}
}
Produces:
export interface Address {
city: string;
zip: string;
}
export interface User {
name: string;
address: Address;
}
export interface RootObject {
user: User;
}
Arrays
Simple Arrays
{ "tags": ["typescript", "javascript"] }
→ tags: string[]
Arrays of Objects
{ "users": [{ "name": "Alice" }, { "name": "Bob" }] }
→ Creates a User interface and types the field as users: User[]
Mixed Arrays
{ "values": [1, "two", true] }
→ values: (number | string | boolean)[]
Best Practices
- Use meaningful root names — Instead of
RootObject, useApiResponse,UserProfile, orOrderData - Review generated types — Auto-generated types are a starting point; refine them for your domain
- Use strict null checks — Enable
strictNullChecksin tsconfig.json to catch null errors at compile time - Export interfaces — Our converter exports all interfaces, making them importable across your project
- Consider readonly — If the data is read-only (API responses), consider adding
readonlyto properties manually