Ttooleras
📘

JSON to TypeScript

JSON Tools

Generate TypeScript interfaces and types from JSON — handle nested, optional, arrays. Free, private — all processing in your browser.

Advertisement

The JSON to TypeScript Converter generates TypeScript interfaces and type definitions from JSON samples. Paste an API response, config file, or any JSON data, and the tool analyzes its structure to produce matching TypeScript interfaces — correct types (string, number, boolean, null), nested objects as nested interfaces, arrays with element types inferred, optional fields (for keys present in some samples but not others), and union types (when same field has different types across samples). Perfect for typing API responses, starting new TypeScript projects, or documenting data structures.

TypeScript adoption has made "what type does this API return?" a daily question. Writing interfaces by hand is tedious and error-prone — especially for complex nested responses. This tool solves it: give it the JSON, get typed interfaces instantly. Supports single-sample inference (types from one example) or multi-sample inference (paste multiple samples; tool computes union types, optional fields where some samples differ). Output uses modern TypeScript idioms — interface over type alias, proper generic arrays, marked optional fields, literal types when values are enum-like.

JSON to TypeScript — key features

Accurate type inference

Correctly infers string, number, boolean, null, arrays, nested objects. Matches modern TypeScript idioms.

Multi-sample input

Paste an array of samples. Tool detects which fields are optional, which have union types.

Nested interface generation

Every nested object becomes its own named interface. Clean, reusable types.

Optional field detection

Fields missing in some samples marked with ? for optional.

Union types

Fields with different types across samples get union types (string | number).

Literal string types

Small set of string values suggested as literal types ("active" | "inactive").

Readonly options

Mark arrays or all properties as readonly for immutability.

Export style

Named exports, default export, or no exports — match your module style.

How to use the JSON to TypeScript

  1. 1

    Paste JSON

    Single sample or array of samples (more samples = better type inference).

  2. 2

    Configure root name

    Top-level interface name. Use API endpoint name or descriptive label.

  3. 3

    Set options

    Readonly? Parse dates? Convert to enums when possible?

  4. 4

    Click Generate

    TypeScript interfaces appear. Each nested object has its own interface.

  5. 5

    Copy to your project

    Paste into your types file. Import and use for type safety.

Common use cases for the JSON to TypeScript

API integration

  • Type API responses: Hit an API endpoint, get JSON response. Convert to TypeScript types for your fetch wrapper.
  • Document API contracts: Generated types serve as living documentation of what APIs return.
  • Third-party API types: When third-party API has no TS types available, generate yours from sample responses.
  • GraphQL response types: Even GraphQL apps benefit from manual type generation for complex nested responses.

Legacy migration

  • Migrate JS to TS: Type existing JS code by inferring types from actual data.
  • Type dynamic data: JSON from databases, cache, storage — generate types for better IDE support.
  • Config file types: If your app reads JSON configs, generate types for validation.

Testing

  • Mock data types: Generate types from mock JSON for test fixtures.
  • Integration tests: Real API responses converted to types ensure tests match actual data.
  • Contract testing: Types as contracts — ensure backend returns expected structure.

Learning

  • Understand TypeScript patterns: See how structures are typed. Learn modern TS idioms.
  • Compare with hand-written types: Generate types and compare with your manual attempt.

JSON to TypeScript — examples

Simple object

Basic type inference.

Input
{
  "name": "Alice",
  "age": 30,
  "active": true
}
Output
interface Root {
  name: string;
  age: number;
  active: boolean;
}

Nested objects

Multiple interfaces generated.

Input
{
  "user": {
    "profile": {
      "email": "a@x.com",
      "verified": true
    },
    "roles": ["admin", "editor"]
  }
}
Output
interface Root {
  user: User;
}

interface User {
  profile: Profile;
  roles: string[];
}

interface Profile {
  email: string;
  verified: boolean;
}

Array of objects

Array type with element interface.

Input
[
  {"id": 1, "name": "Alice"},
  {"id": 2, "name": "Bob"}
]
Output
type Root = Item[];

interface Item {
  id: number;
  name: string;
}

Optional field (multi-sample)

Field missing in some samples.

Input
[
  {"id": 1, "email": "a@x.com"},
  {"id": 2}
]
Output
interface User {
  id: number;
  email?: string;  // optional — not in all samples
}

Union type

Field with different types.

Input
[
  {"value": "text"},
  {"value": 42}
]
Output
interface Item {
  value: string | number;
}

Literal string union

Enum-like status field.

Input
[
  {"status": "active"},
  {"status": "inactive"},
  {"status": "pending"}
]
Output
interface Item {
  status: "active" | "inactive" | "pending";
}

Complex API response

Nested arrays of objects.

Input
{
  "users": [
    {"id": 1, "tags": ["a"]},
    {"id": 2, "tags": []}
  ],
  "total": 2
}
Output
interface Root {
  users: User[];
  total: number;
}

interface User {
  id: number;
  tags: string[];
}

Technical details

Type inference from JSON:

Primitive types:

| JSON value | TypeScript type |
|---|---|
| "hello" | string |
| 42 | number |
| 3.14 | number |
| true/false | boolean |
| null | null |

Arrays:

- Empty array []unknown[] or never[].
- Array of same type [1, 2, 3]number[].
- Array of objects [{id:1}, {id:2}]{id: number}[].
- Mixed types [1, "two"](number | string)[].

Objects:

Each object becomes an interface. Nested objects become nested interfaces.

``json
{
"user": {
"name": "Alice",
"age": 30
}
}
``

```typescript
interface Root {
user: User;
}

interface User {
name: string;
age: number;
}
```

Optional fields:

With multi-sample input:

``json
[
{"id": 1, "email": "a@x.com"},
{"id": 2}
]
``

``typescript
interface User {
id: number;
email?: string; // optional because not in all samples
}
``

Union types:

When same field has different types:

``json
[
{"value": "text"},
{"value": 42}
]
``

``typescript
interface Item {
value: string | number;
}
``

Literal types (enum-like):

When field values are a small set:

``json
[
{"status": "active"},
{"status": "inactive"},
{"status": "pending"}
]
``

``typescript
interface Item {
status: "active" | "inactive" | "pending";
}
``

Naming:

- Top-level interface: Root or configurable (e.g., use URL path for API).
- Nested interfaces: inferred from key name (capitalized). userUser.
- Collision handling: User1, User2 if different structures share name.

Modern TS features:

- Readonly arrays: Option to mark all arrays as readonly T[] (immutability).
- Readonly properties: Option to mark all properties as readonly.
- null vs undefined: Distinction preserved. Optional (?) means possibly undefined; explicit null means value is null.
- Utility types: Generated interfaces work well with Partial<T>, Pick<T, K>, Omit<T, K>.

Advanced features:

- Detect date strings: "2026-05-05"string by default, or Date (if "Parse dates" option enabled — note TypeScript has no built-in Date type distinct from string).
- Detect enums: 3+ distinct string values used → suggest enum.
- Detect arrays of empty structures: [] with context clues → AnyType[].

Import/export options:

- Named exports for each interface.
- Default export of root.
- Export everything.
- Private (no export — internal use).

Common pitfalls:

- Single sample mistakes: email: null in one sample → inferred as null type. If email is sometimes string, provide multi-sample.
- Empty arrays/objects: [] and {} give limited information. Use non-empty samples.
- Very deeply nested: Result can be overwhelming. Extract sub-types for clarity.

Alternative tools:

- quicktype (the canonical tool for this, CLI and web).
- json2ts (VS Code extension).
- ts-json-schema-generator (TypeScript → JSON Schema, opposite).

This formatter inspired by quicktype's approach.

Common problems and solutions

Single sample misses optional fields

Field present in one sample assumed required. Provide multiple samples to discover optional fields. Or manually add ? after generation.

null fields inferred as null type

A field with only null values becomes type null — rarely useful. Provide sample where field has actual value. Or post-edit to `string | null`.

Dates inferred as strings

TypeScript has no built-in date distinction from string. Options: (1) keep as string, parse when needed. (2) Use Date type and parse on input/output. (3) Use a tagged type like ISODate = string.

Arrays of mixed types complicate

Mixed-type arrays produce union types. May not reflect what you want. Consider whether data should be homogeneous, or use discriminated unions.

Very deeply nested

10+ levels of nesting produce many interfaces. Consider flattening the JSON structure or breaking into separate top-level types.

Name collisions

Tool generates names from keys. Multiple User interfaces for different structures collide. Tool appends numbers (User1, User2) — consider manually refactoring.

Large enums

Many string values become long union types. Consider if a proper enum is more appropriate. Or use string type with JSDoc for known values.

Circular references

Tree-like JSON (each node references parent) inferred as deep nested types. TypeScript has no built-in circular types — reference by interface name.

JSON to TypeScript — comparisons and alternatives

JSON to TypeScript vs quicktype: quicktype is the canonical tool with CLI, VS Code, and web interfaces. Supports many target languages (TS, Python, Go, Rust). This tool focuses on TS with clean output.

Interface vs Type alias: Interfaces for object shapes (generated here). Type aliases for unions, intersections. Interfaces preferable for API types (can be extended).

Manual vs generated types: Generated saves time, catches details you might miss. Manual gives more control (better naming, precise optionality). Use generated as starting point, refine.

JSON Schema to TS vs JSON to TS: JSON Schema is explicit type description. JSON is example data. From JSON Schema you get more precise types (required fields, formats). From JSON sample, you get inferred types.

Runtime vs compile-time types: TypeScript types are compile-time (erased in JS output). For runtime validation, pair types with Zod, Yup, or io-ts — validate JSON matches expected type at runtime.

TypeScript vs Flow: Flow (Facebook's type checker) similar to TS but less adopted. TS is dominant. Generated types here target TypeScript.

Frequently asked questions about the JSON to TypeScript

How does JSON to TypeScript conversion work?

Tool analyzes JSON structure and generates matching TypeScript interfaces. Primitive types (string, number, boolean) mapped directly. Objects become interfaces. Arrays become typed arrays (T[]). Nested objects get their own interfaces. Result is TypeScript that describes the JSON's shape.

Do I need multiple samples?

Recommended. Single sample gives types based on that one example — assumes all fields required, all optional fields missed. Multiple samples let the tool detect which fields are optional (missing in some) and which have union types (different values across samples).

How does it handle optional fields?

With multi-sample input: fields present in some samples but not others become optional (?). With single-sample: all fields assumed required. Post-edit to add ? where needed.

Is my JSON safe here?

Yes. Analysis happens in your browser. JSON never uploads. Safe for proprietary API responses, internal data structures.

What about dates?

JSON does not have a date type — dates are strings ("2026-05-05"). TypeScript does not have a string-tagged-as-date type. Options: (1) keep as string. (2) Convert to Date in your code after parsing. (3) Use branded types: type ISODate = string & { _brand: "ISODate" }.

Does it generate enums?

Literal union types by default: status: "active" | "inactive". Can generate proper enums with option. Unions are simpler and often preferred in modern TS.

Can I use for GraphQL?

Not the primary use case. GraphQL has its own codegen tools (graphql-codegen) that generate types from schema. But if you have example GraphQL responses, this tool can type them.

What about validation?

TypeScript types are compile-time only — erased at runtime. For runtime validation, use libraries like Zod, Yup, io-ts. These integrate with TypeScript types.

Can it handle complex nested JSON?

Yes. Deep nesting produces many interfaces, one per unique object shape. Result may be overwhelming but accurate. Consider refactoring very deep structures.

Interface or type alias?

Tool uses interfaces for object shapes (better for extending, standard convention). Uses type aliases for union types (T | U) and array types. Matches modern TypeScript best practices.

Additional resources

Advertisement

Related tools

All JSON Tools

Learn more

Explore more tools

200+ free tools that run in your browser.

Browse all tools →