DEV Community

黃彥鈞
黃彥鈞

Posted on

Generate Clean TypeScript Interfaces From Nested JSON Locally (Zero Server Uploads)

Every backend integration starts the same way: you hit a new REST or GraphQL endpoint, grab a 120-line nested JSON response, and need strict TypeScript interfaces fast.

Pasting internal or staging API payloads into random cloud converters isn't great for security. Fortunately, writing a deterministic JSON-to-TypeScript type inferrer in pure browser JS takes under 40 lines.

Core Recursive Type Inference Logic

function inferTsType(value: unknown, name = 'Root'): string {
  if (value === null) return 'null';
  if (Array.isArray(value)) {
    if (value.length === 0) return 'unknown[]';
    const itemType = inferTsType(value[0], `${name}Item`);
    return `${itemType}[]`;
  }
  if (typeof value === 'object') {
    const entries = Object.entries(value as Record<string, unknown>)
      .map(([k, v]) => `  ${/^[a-zA-Z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${inferTsType(v, k)};`)
      .join('\n');
    return `{\n${entries}\n}`;
  }
  return typeof value;
}
Enter fullscreen mode Exit fullscreen mode

Use the Ready-Made Offline Converter (JSON → TypeScript / YAML / CSV)

I bundled an enhanced version (handling union arrays, optional keys, YAML export, and flattened CSV) into a static zero-login browser toolbox:

Everything runs 100% locally in your tab—open DevTools Network tab to verify zero outbound requests!

Top comments (0)