Free online tool

Upload a file

Drop your file hereTap to choose a file

or click to browse, or paste from the clipboard

← Back to Blog

JSON to TypeScript: How to Generate Interfaces and Types from JSON

To convert JSON to TypeScript, paste a representative sample into a generator that reads every value and writes an interface or type alias for each object: strings become string, numbers number, nested objects get their own named types and arrays become T[]. Then check what a sample cannot prove: which keys are optional, which can be null, whether IDs fit in a JavaScript number, and whether real data will match at runtime. The JSON to TypeScript Converter does the first part in your browser. This guide covers the second, with a worked example from the converter's real output.

How to convert JSON to TypeScript with Zutilium

  1. Open the JSON to TypeScript Converter. It starts with an example, so select Clear, then paste your JSON into the JSON box, choose Open file or drop a .json file onto it.
  2. To give the converter more evidence, paste several records inside one pair of square brackets. All the objects in an array merge into one type.
  3. Enter a Root type name. For an array, use a plural: Orders gives Orders = Order[], while Order would name the items OrderItem.
  4. Under Options, choose Declare with interface or type, and set null values and Keys some objects lack as explained below. On a phone, tap Options to open the panel.
  5. Read the declarations and the notes under them, which flag always-null keys, always-empty arrays, renamed types and integers too large for JavaScript.
  6. Select Copy or Download types.ts, then add the declarations to your project.

The output updates as you type, and the status line under the panes counts declarations, properties and optional properties, a quick check on whether a sample made too many keys optional. Parsing runs on the page, so nothing you paste is uploaded.

JSON to TS: how each value becomes a TypeScript type

JSON has six kinds of value: objects, arrays, strings, numbers, booleans and null. There is no date, integer or undefined, so a generator maps only what is there:

JSON in the sample Generated TypeScript
"Ada" string
49.9 or 2 number
true boolean
{"name": "Ada"} A named interface, such as Customer
{} Record<string, unknown>
["a", "b"] string[]
[] unknown[], with a note
[1, "a"] (string | number)[]
"2026-11-20T14:05:00Z" string, with an ISO 8601 comment
null null, usually in a union such as string | null

Dates stay string because JSON.parse returns strings. Type a key as Date only after your own code converts it with new Date().

Worked example: two API responses, one interface

Suppose an endpoint returns one order at a time and you saved two responses. Paste them together as an array and set Root type name to Orders:

[
  {
    "id": 1179849503426199553,
    "status": "paid",
    "total": 49.9,
    "placedAt": "2026-11-20T14:05:00Z",
    "customer": { "name": "Ada Lovelace", "email": "ada@example.com" },
    "line_items": [{ "sku": "BK-01", "qty": 2 }],
    "coupon": null,
    "tags": []
  },
  {
    "id": 1179849503426199554,
    "status": "refunded",
    "total": "15.00",
    "placedAt": "2026-11-21T09:12:44Z",
    "customer": { "name": "Grace Hopper", "email": null },
    "line_items": [{ "sku": "MUG-3", "qty": 1, "giftWrap": true }],
    "tags": []
  }
]

With the default options, the converter returns:

export type Orders = Order[];

export interface Order {
  id: number; // JSON.parse reads 1179849503426199553 as 1179849503426199552 (2 integers beyond 2^53 - 1)
  status: string;
  total: string | number;
  placedAt: string; // ISO 8601 date-time
  customer: Customer;
  line_items: LineItem[];
  coupon?: null;
  tags: unknown[];
}

export interface Customer {
  name: string;
  email: string | null;
}

export interface LineItem {
  sku: string;
  qty: number;
  giftWrap?: boolean;
}

The status line reads "4 declarations, 13 properties (2 optional)." Every line matches the sample, but several need a decision only you can make:

Generated line What the sample showed What to do
id: number IDs beyond 2⁵³ − 1 Use string (see large IDs below)
status: string Two different words Narrow to "paid" | "refunded" if the API documents them
total: string | number 49.9 once, "15.00" once Ask which form the API promises
coupon?: null Null once, missing once Replace null with the real type
tags: unknown[] Only empty arrays Add the item type
email: string | null One null email Keep it and handle null in code

The converter never guesses literal unions such as "paid" | "refunded", and a sample could not show the full list anyway. After those decisions, the edited interface might read:

export interface Order {
  id: string;
  status: "paid" | "refunded";
  total: number;
  placedAt: string; // ISO 8601 date-time
  customer: Customer;
  line_items: LineItem[];
  coupon?: string | null;
  tags: string[];
}

Optional properties and null: what a sample can prove

A sample shows three states, and TypeScript writes each one differently:

  • Present every time: name: string. Present in your samples, which is not a promise from the API.
  • Sometimes null: email: string | null. The key is there and the value can be null, as JSON.parse returns it.
  • Sometimes missing: giftWrap?: boolean. Reading an absent key gives undefined, which JSON itself does not have.

A key that is null in some records and missing from others gets both: discount?: number | null. Two options change how these cases are written:

  • null values: the default, Keep null (key: T | null), matches the parsed data. Make the key optional (key?: T) leaves null out, so the types fit your data only after you remove nulls yourself; a note says so.
  • Keys some objects lack: with exactOptionalPropertyTypes on (TypeScript 4.4 and later, not part of strict), key?: T means absent or a T, never an explicit undefined. Parsed JSON fits that, but if your code builds these objects from values that may be undefined, choose key?: T | undefined.

All of this assumes strictNullChecks, which strict turns on; without it, TypeScript ignores null and undefined.

The bigger risk is a small sample: a key that appeared in every record looks required, and a key that was always a string is typed string, so code that trusts it fails on the first null. Collect responses from different cases, such as a guest checkout, a coupon order and a refund, and paste them as one array. JSON Diff shows how two responses differ, path by path, as the guide to comparing two JSON files explains.

Interface or type alias for JSON data

For plain JSON objects, interface Order { … } and type Order = { … } describe the same shape and accept the same data. The TypeScript handbook calls the choice mostly personal preference and suggests interface until you need a feature only type has (Everyday Types). The differences that matter here:

Feature interface type
Describe a JSON object Yes Yes
Name an array or union No Yes
Build on another type extends & (intersection)
Same name declared twice Members merge Duplicate identifier error

The second row is why the converter writes a top-level array as a type alias, such as export type Orders = Order[], even when you choose interface.

The last row matters for naming. A file with no top-level import or export is a script whose declarations share the global scope (Modules). In a project that includes the DOM library, interface Comment { id: string } in such a file merges with the browser's built-in Comment node, so TypeScript expects dozens of DOM properties on every comment, while type Comment = … fails as a duplicate identifier. With Add export checked, as it is by default, the file is a module and your names stay local.

Naming: why a type is called PostComment

Each object type takes its key's name in PascalCase (user_profile → UserProfile), and array items use the singular of the last word (line_items → LineItem). When the last word is not a clear plural, as with data, the item type is DataItem. Identical shapes share one declaration, and if two different shapes would end up with the same name, the later one becomes ShippingAddress (parent plus key) or gets a number.

It also never reuses one of the 1,498 built-in global names it knows, such as Comment, Event and Response. A comments array under a Post root becomes PostComment, a top-level event key becomes RootEvent, and a note lists the renames.

Keys that are not valid identifiers stay quoted, as in "display-name": string, and you read them with brackets: profile["display-name"].

Large IDs: when number is the wrong type

JavaScript numbers can hold every integer exactly only up to 2⁵³ − 1, or 9,007,199,254,740,991 (Number.MAX_SAFE_INTEGER). JSON itself sets no limit on digits, so 64-bit database IDs often go past it. In the worked example, JSON.parse turns both 1179849503426199553 and 1179849503426199554 into the same number, exactly 1179849503426199552, which JavaScript prints as 1179849503426199600. Two orders now share one ID, and id: number compiles without complaint.

The converter reads the original digits, so it catches this: the property gets a comment, and a note names the first affected path, here $[0].id. The fixes, in order of preference:

  1. Send IDs as strings. Many APIs already do: Discord's HTTP API returns its 64-bit snowflake IDs as strings to prevent integer overflow (Discord API reference). Then type them string.
  2. Keep the digits while parsing. If the API sends bare numbers, changing the type alone does nothing, because JSON.parse has already rounded them. The guide to invalid JSON shows a JSON.parse reviver that reads the original text.

Why TypeScript types are not runtime validation

TypeScript removes types when it compiles, and the handbook states that type annotations never change how your program behaves at runtime (The Basics). JSON.parse is declared to return any, and TypeScript's DOM library types response.json() as Promise<any>, so const order: Order = await res.json() compiles whatever the server sends.

Check outside data where it enters your app. A schema library such as Zod lets you write the shape once and get both the check and the type (Zod basics):

import * as z from "zod";

const OrderSchema = z.object({
  id: z.string(),
  status: z.enum(["paid", "refunded"]),
  total: z.number(),
  placedAt: z.string(),
  customer: z.object({ name: z.string(), email: z.string().nullable() }),
  line_items: z.array(z.object({ sku: z.string(), qty: z.number(), giftWrap: z.boolean().optional() })),
  coupon: z.string().nullable().optional(),
  tags: z.array(z.string()),
});

type Order = z.infer<typeof OrderSchema>;

const res = await fetch("/api/orders/42");
const order = OrderSchema.parse(await res.json()); // typed as Order, throws a ZodError if the shape is wrong

The schema expects string IDs, as recommended above, and rejects a total sent as "15.00", so drift like the second sample's is reported as soon as the data arrives. Use safeParse to handle failures without exceptions; it returns { success: true, data } or { success: false, error }. By default z.object also strips keys it does not list. Ajv does the same job with a JSON Schema. Either way, the generated interface is a quick first draft of the schema, not a replacement for it.

When a sample is the wrong source of types

Your situation Better source of types
A JSON file inside your project Import it with resolveJsonModule
An API with an OpenAPI description Generate from the spec (openapi-typescript)
A JSON Schema document Compile it (json-schema-to-typescript)
Data you validate at runtime Write the Zod schema, then use z.infer
Undocumented or one-off responses Generate from samples, then review

For a file in your repository, turn on resolveJsonModule and TypeScript types the import from the file itself, so there is nothing to keep in sync:

import settings from "./settings.json";

type Settings = typeof settings;

With module set to nodenext, TypeScript 5.7 and later also require with { type: "json" } on that import. A spec beats a sample because it lists every field and says which are required.

Troubleshooting

"The JSON has an error, so the TypeScript is not updated"

The message gives a line and column, such as "Line 4, column 1: Expected a quoted property name. Remove the comma before }." Select Go to line 4, column 1 to jump there. The invalid JSON guide covers the usual causes, and the JSON Formatter & Validator checks syntax on its own.

"Unexpected content after the root value"

You pasted two documents back to back, such as two saved responses or JSON Lines. Put them inside [ ] with commas between them, which is also how you merge samples.

Too many optional keys or unexpected unions

The array probably mixes different kinds of object, such as an error response among full records. Remove those, or generate their types separately.

A large export is slow or over the limit

The converter reads up to 5 MiB (5,242,880 bytes) and 128 levels of nesting. Input over 100,000 characters or 1,000 objects converts in a background worker, and Copy and Download types.ts always include the full result. Variety matters more than volume: a smaller file gives the same types as long as it keeps every variation, such as records with missing keys or nulls.

Frequently asked questions

How do I create a TypeScript interface from JSON?

Paste the JSON into the JSON to TypeScript Converter, set Declare with to interface and select Copy. Each object becomes an interface named after its key, and all the objects in an array merge into one. Then review optional keys, nulls and numeric IDs, because the converter only knows your sample.

Should I use an interface or a type for JSON data?

Either works for JSON data. The TypeScript handbook suggests interface until you need a type-only feature such as naming a union. The one trap is declaration merging, so export your types and avoid global names like Comment.

Does TypeScript check JSON.parse results at runtime?

No. Types are erased when your code compiles, and JSON.parse returns any, so JSON.parse(text) as Order compiles whatever the text contains. Treat the result as unknown and validate it where it enters your app, for example with a Zod schema's parse method, which returns typed data or throws.

Can I generate TypeScript types from a CSV file?

Convert it to JSON first with the CSV to JSON Converter, which keeps long IDs and ZIP codes as text, then paste the result. The CSV to JSON guide explains its output shapes.

Is my JSON uploaded when I convert it?

No. Parsing and type inference happen in your browser, so the JSON never leaves it and is never stored. The converter remembers only your option settings.