Generating TypeScript types from sample JSON

Published: 2026-05-17

How tools infer interfaces from example payloads, what one sample cannot prove, and how to tighten types after generation—all in the browser on LocalTools.

Sample JSON is often the fastest way to sketch TypeScript types: you paste a response body or config snippet and get interface or type aliases that match the shape. That is heuristic, not a full schema: the generator only sees one instance of the data.

What “generate types from JSON” usually does

A typical pipeline:

  1. Parse the text as JSON (strict: no comments or trailing commas unless the tool explicitly supports JSONC).
  2. Walk the resulting value and emit a type for each object property, array element union, and primitive.
  3. Name nested objects (often Root, User, Item, or numbered suffixes) so the output compiles.

Arrays become SomeType[] or unions like (string | number)[] when elements differ. Objects become interfaces with required properties by default; some tools add ? for keys that appear missing in sibling objects merged from an array.

What one sample cannot know

Generators guess from values they saw, not from rules the API guarantees:

  • Optionality: A field absent in your sample might be optional—or simply missing this time. Conversely, a present field might be optional in the real schema.
  • Unions vs string literals: "status": "active" might become status: "active" (literal) or status: string. Wider APIs need string or a hand-maintained union.
  • Numbers vs integers: JSON has one number type; TypeScript can use number everywhere or you can narrow to bigint / branded types yourself.
  • Dates and IDs: ISO date strings are still string at the type level unless you map them to Date or a branded type in application code.
  • Maps vs objects: JSON objects with dynamic keys often become Record<string, T> only if the tool detects heterogeneous keys; otherwise you get a fixed interface.

For authoritative contracts, prefer OpenAPI, JSON Schema, or GraphQL codegen when you have them; sample-driven types are best for exploration, fixtures, and quick adapters.

Practical tips after you paste

  1. Validate JSON first with a formatter so you are not inferring from a half-edited blob.
  2. Rename generated root and nested types to match your domain (ApiUser, not Root2).
  3. Widen unstable fields (unknown for truly opaque blobs, or string instead of a single literal if more values exist in production).
  4. Add readonly or as const at call sites if you treat responses as immutable snapshots.

Try it locally in your browser

Use the JSON to TypeScript tool to turn sample JSON into types without uploading files. To format or validate the JSON first, use the JSON Formatter & Validator. On LocalTools, parsing and generation stay in your browser.

Related reading

All learn articles