Build a Recursive JSON-to-TypeScript Interface Generator in 60 Lines (Zero Dependencies)
Every TypeScript developer has pasted an undocumented REST API payload into an editor and started manually typing interface ApiResponse { ... } . Most quick "JSON to TypeScript" snippets you find online only inspect the first item of an array and run naive typeof value checks. On real production APIs, that immediately breaks in four ways: Optional properties disappear: Item 0 does not have…
Every TypeScript developer has manually typed interfaces for API responses in the past. Most online "JSON to TypeScript" snippets only look at the first item of an array and perform naive typeof value checks. However, real production APIs break quickly in four ways: optional properties disappear, nullable fields become problematic, hyphenated keys cause syntax errors, and nested objects merge or become unreadable.
This article explains how to create a clean, recursive JSON-to-TypeScript interface generator in just 60 lines of zero-dependency TypeScript that handles all four edge cases properly. The approach combines naive typeof inference with merged schema inference to produce accurate TypeScript interfaces.
The module operates in pure TypeScript and can run in any environment without requiring any npm dependencies. It defines a regular expression for valid identifier names, a function to convert keys to PascalCase, and a function to format keys for TypeScript syntax. The main function, jsonToTypeScript, takes the input data and an optional root name, and returns a string containing the generated TypeScript interfaces.
It utilizes two helper functions, infer and inferArray, to recursively analyze the input data and infer the appropriate TypeScript types.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to