Convert Nested JSON Objects to TypeScript Interfaces
Learn how to generate multiple TypeScript interfaces from a JSON object with nested sub-objects. Includes tips on naming and flattening strategies.
Detailed Explanation
Handling Nested Structures
Real-world JSON is rarely flat. APIs typically return objects inside objects, and each level of nesting maps to a separate TypeScript interface.
Example JSON
{
"id": 1,
"name": "Acme Corp",
"address": {
"street": "123 Main St",
"city": "Springfield",
"geo": {
"lat": 39.7817,
"lng": -89.6501
}
}
}
Generated TypeScript
interface Geo {
lat: number;
lng: number;
}
interface Address {
street: string;
city: string;
geo: Geo;
}
interface Company {
id: number;
name: string;
address: Address;
}
Why Separate Interfaces?
Extracting each nested object into its own interface provides several benefits:
- Reusability —
Geocan be reused anywhere coordinates appear (e.g., store locations, event venues). - Readability — A deeply nested inline type like
{ street: string; city: string; geo: { lat: number; lng: number } }quickly becomes hard to read. - Testability — You can write tests and mock data for
Addressindependently ofCompany.
Naming Conventions
The converter derives interface names from the property key in PascalCase. If two properties at different paths share the same name but different shapes, the converter appends a numeric suffix or nests the name (e.g., UserAddress vs OrderAddress). You should review generated names and rename them to match your domain language.
Depth Limits
Extremely deep nesting (5+ levels) is a code smell. Consider whether the JSON can be redesigned, or flatten intermediate layers into a single interface with dotted-path comments for documentation.
Use Case
You are integrating a third-party API that returns deeply nested company data with address and geolocation sub-objects, and you need type-safe access to every level.
Try It — JSON to TypeScript
Related Topics
Convert a Simple JSON Object to a TypeScript Interface
Basic Conversions
Convert JSON Arrays of Objects to TypeScript Types
Basic Conversions
Generate Recursive TypeScript Types from Self-Referencing JSON
Complex Types
Type a Full API Response JSON as TypeScript
Advanced Patterns
Handle Optional and Nullable Fields in TypeScript from JSON
Type Refinements