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
"avatarUrl", while Item 1 does - a naive generator misses"avatarUrl"?: stringcompletely. - Nullable fields break strict mode: Item 0 has
"deletedAt": nulland Item 1 has"deletedAt": "2026-11-26". You needstring | null, notanyornull. - Hyphenated / non-identifier keys cause syntax errors: Keys like
"user-id"or"2fa_enabled"must be quoted as"user-id": string. - Nested objects collide or turn into unreadable inline blobs: Extracting clean PascalCase interfaces makes the output immediately usable in your codebase.
Here is how to build a clean, recursive JSON-to-TypeScript interface generator in ~60 lines of zero-dependency TypeScript that handles all four edge cases properly.
Naive typeof vs. Merged Schema Inference
| Real-World API Payload | Naive typeof Generator | Merged Recursive Inference |
|---|---|---|
[{ id: 1 }, { id: 2, tag: "pro" }] | { id: number }[] (drops tag!) | { id: number; tag?: string }[] |
[{ role: null }, { role: "admin" }] | { role: null }[] | `{ role: string |
{% raw %}{ "x-rate-limit": 60 } | x-rate-limit: number; (syntax error!) | "x-rate-limit": number; |
[] (empty array) | any[] | unknown[] |
The Complete 60-Line Recursive Implementation
This pure TypeScript module runs anywhere (browser, Node.js, Bun, Deno, or VS Code extensions) with zero npm dependencies:
const VALID_IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/; function toPascalCase(key: string): string { const cleaned = key .replace(/[^a-zA-Z0-9]+(.)/g, (_, chr: string) => chr.toUpperCase()) .replace(/[^a-zA-Z0-9]/g, ""); const name = cleaned ? cleaned[0].toUpperCase() + cleaned.slice(1) : "Item"; return /^[0-9]/.test(name) ? `Item${name}` : name; } function formatKey(key: string): string { return VALID_IDENT.test(key) ? key : JSON.stringify(key); } export function jsonToTypeScript( input: unknown, rootName = "RootResponse" ): string { const interfaces = new Map<string, string>(); function infer(value: unknown, nameHint: string): string { if (value === null) return "null"; if (Array.isArray(value)) return inferArray(value, nameHint); if (typeof value === "object") { return inferObject([value as Record<string, unknown>], nameHint); } return typeof value; // "string" | "number" | "boolean" } function inferArray(items: unknown[], nameHint: string): string { if (items.length === 0) return "unknown[]"; const objects = items.filter( (x): x is Record<string, unknown> => x !== null && typeof x === "object" && !Array.isArray(x) ); const nonObjects = items.filter( (x) => x === null || typeof x !== "object" || Array.isArray(x) ); const types = new Set<string>(); const singularHint = nameHint.endsWith("s") ? nameHint.slice(0, -1) : `${nameHint}Item`; if (objects.length > 0) { types.add(inferObject(objects, singularHint)); } for (const item of nonObjects) { types.add(infer(item, singularHint)); } const union = Array.from(types).join(" | "); return types.size > 1 ? `(${union})[]` : `${union}[]`; } function inferObject( samples: Record<string, unknown>[], nameHint: string ): string { const ifaceName = toPascalCase(nameHint); const keyCounts = new Map<string, number>(); const keyTypes = new Map<string, Set<string>>(); for (const obj of samples) { for (const [k, v] of Object.entries(obj)) { keyCounts.set(k, (keyCounts.get(k) || 0) + 1); if (!keyTypes.has(k)) keyTypes.set(k, new Set()); keyTypes.get(k)!.add(infer(v, k)); } } const lines = Array.from(keyTypes.entries()).map(([k, typeSet]) => { const isOptional = (keyCounts.get(k) || 0) < samples.length; const mergedType = Array.from(typeSet).join(" | "); return ` ${formatKey(k)}${isOptional ? "?" : ""}: ${mergedType};`; }); interfaces.set( ifaceName, `export interface ${ifaceName} {\n${lines.join("\n")}\n}` ); return ifaceName; } const rootType = infer(input, rootName); const blocks = Array.from(interfaces.values()); if (!interfaces.has(rootType)) { blocks.push(`export type ${toPascalCase(rootName)} = ${rootType};`); } return blocks.join("\n\n"); } Testing It on a Messy Real-World API Payload
Pass a typical array response with nulls, optional fields, and hyphenated keys:
const sample = [ { id: 1, role: null, meta: { active: true } }, { id: 2, role: "admin", "user-tag": "pro", meta: { active: false } }, ]; console.log(jsonToTypeScript(sample, "Users")); Generated output:
export interface Meta { active: boolean; } export interface User { id: number; role: null | string; meta: Meta; "user-tag"?: string; } export type Users = User[]; Every single edge case - null | string, "user-tag"?: string, nested Meta interface, and top-level array alias export type Users = User[] - comes out cleanly typed and ready to paste into strict TypeScript.
Try It Live in Your Browser (Zero Uploads)
Never paste private production API payloads (containing tokens, customer emails, or internal schemas) into server-backed converters. Both of our browser utilities run 100% locally client-side:
- OmniTools JSON to TypeScript & Schema Generator - Instant TypeScript interfaces & schemas from any JSON payload with zero server upload.
- OmniTools JSON Formatter & Validator - Prettify, validate syntax errors, and convert JSON to CSV locally in your browser.
Key Takeaways
- Always merge all object samples inside JSON arrays so optional (
?) and nullable (| null) fields are inferred accurately. - Use
unknown[]instead ofany[]for empty arrays to keepstrict: truecodebases safe. - Always quote property keys that fail
/^[A-Za-z_$][A-Za-z0-9_$]*$/so generated interfaces compile on the first try.
Do you prefer generating plain TypeScript interfaces or runtime validators like Zod schemas from API responses? Share your workflow in the comments!
