Generate TypeScript types from JSON, and when to use Zod instead
By Hammad Rasool · November 11, 2026
Quick answer: paste a real JSON response into the JSON to TypeScript converter to get interfaces in a second, then fix the fields one sample can't describe: values that were null, empty arrays, strings that are really a fixed set of values, and dates. Those types only check your code. If the data comes from an API, a file or a user, add a runtime schema with Zod and let it produce the type, so a bad response fails where it arrives instead of somewhere deep in your code.
How this was tested: on 11 November 2026 the samples below were converted with ToolStash's own converter code, the output was compiled with TypeScript 6.0.3 in strict mode and run on Node.js 24.18.1, and the schema example was run with Zod 4.6.7. Every error message and output on this page is copied from those runs.
Step 1: Generate the types from a real response
Use a real response, not a hand-written one: real data has the nulls and odd values you need to see.
{
"id": 1042,
"status": "paid",
"createdAt": "2026-11-11T09:30:00Z",
"customer": { "name": "Sara Khan", "email": "sara@example.com", "phone": null },
"items": [
{ "sku": "A-001", "qty": 2, "price": 12.5 },
{ "sku": "B-210", "qty": 1, "price": 4.99, "discount": 0.5 }
],
"tags": [],
"shipping-address": { "city": "Multan", "zip": "60000" }
}The converter's output:
export interface Customer {
name: string;
email: string;
phone: null;
}
export interface Item {
sku: string;
qty: number;
price: number;
discount?: number;
}
export interface ShippingAddress {
city: string;
zip: string;
}
export interface Order {
id: number;
status: string;
createdAt: string;
customer: Customer;
items: Item[];
tags: unknown[];
"shipping-address": ShippingAddress;
}What it worked out on its own:
- A separate interface for each nested object, named from its key (
customer→Customer,items→Item). discount?is optional because one item had it and the other didn't."shipping-address"is quoted, because a hyphen isn't allowed in a bare property name.
Step 2: Fix what one sample can't tell you
A converter can only describe the values it sees. These generated types compiled, but strict TypeScript then rejected normal code that uses them:
o.customer.phone = "0300-1234567";
// error TS2322: Type '"0300-1234567"' is not assignable to type 'null'.
const d: number = o.items[0].discount;
// error TS2322: Type 'number | undefined' is not assignable to type 'number'.
o.createdAt.getFullYear();
// error TS2339: Property 'getFullYear' does not exist on type 'string'.Each error points at a field to edit by hand:
| Generated | Why | Change it to |
|---|---|---|
phone: null | The only value seen was null | phone: string | null |
tags: unknown[] | The array was empty | tags: string[] (or the real item type) |
status: string | JSON has no enums | "pending" | "paid" | "shipped" |
createdAt: string | JSON has no date type | Keep string; convert with new Date(createdAt) where you need a date |
discount?: number | Missing in one item | Correct. Handle it with i.discount ?? 0 |
After editing:
export interface Customer {
name: string;
email: string;
phone: string | null; // null in the sample, a string for other customers
}
export interface Order {
id: number;
status: "pending" | "paid" | "shipped"; // the values your API documents
createdAt: string; // ISO date string; convert with new Date(...)
customer: Customer;
items: Item[];
tags: string[]; // empty in the sample
"shipping-address": ShippingAddress;
}Arrays show you more than single objects
With an array of records, the converter compares every item, which reveals problems a single object hides:
[
{ "id": 1, "name": "Sara", "role": "admin", "lastLogin": "2026-11-10T08:00:00Z" },
{ "id": 2, "name": "Ali", "role": "editor", "lastLogin": null },
{ "id": "3", "name": "Hina", "role": "viewer" }
]export interface User {
id: string | number;
name: string;
role: string;
lastLogin?: string | null;
}
export type UserList = User[];id: string | number means the API sent "3" for one user: worth asking the API owner about rather than keeping in your types. lastLogin?: string | null shows the field can be missing and null, two different cases your code must handle. Paste several records, not one, whenever you can.
Step 3: Know what the types don't do
TypeScript types disappear when the code is compiled. JSON.parse and res.json() return any, so a cast with as Order is a promise you make to the compiler, not a check:
const order = JSON.parse('{"id": 7, "status": "paid", "items": "none"}') as Order;
total(order); // compiles without an error
// At runtime:
// TypeError: o.items.reduce is not a functiontsc --strict reported no errors for this file, and Node.js threw the TypeError when it ran. If the response changes shape, because of an API update, an error page or a field that is sometimes missing, the failure shows up far from the cause.
Step 4: Add Zod when the data comes from outside
A Zod schema describes the same shape as the interface, but it runs. z.infer turns it into a TypeScript type, so you write the shape once:
import * as z from "zod";
const OrderSchema = z.object({
id: z.number(),
status: z.enum(["pending", "paid", "shipped"]),
createdAt: z.iso.datetime(),
customer: z.object({
name: z.string(),
email: z.email(),
phone: z.string().nullable(),
}),
items: z.array(z.object({
sku: z.string(),
qty: z.number().int(),
price: z.number(),
discount: z.number().optional(),
})),
tags: z.array(z.string()),
"shipping-address": z.object({ city: z.string(), zip: z.string() }),
});
type Order = z.infer<typeof OrderSchema>; // the type comes from the schema
const result = OrderSchema.safeParse(await res.json());
if (!result.success) {
console.error(result.error.issues);
} else {
total(result.data); // result.data is a checked Order
}The real order.json above passed. The broken response from step 3 failed with one issue per wrong field, printed as path: message:
createdAt: Invalid input: expected string, received undefined
customer: Invalid input: expected object, received undefined
items: Invalid input: expected array, received string
tags: Invalid input: expected array, received undefined
shipping-address: Invalid input: expected object, received undefinedThat points straight at the problem, while the plain cast produced a TypeError inside total(). Use the generated interfaces as the starting point for the schema; the field list is the same.
Interfaces or Zod?
| Situation | Use |
|---|---|
| Data your own code creates and passes around | Interfaces or type aliases |
| Responses from an API you control, with tests on both sides | Interfaces (shared from one package if you can) |
| Third-party APIs, webhooks, uploaded files, form input, environment variables | A Zod schema, with the type from z.infer |
| A quick script or a one-off exploration | Generated interfaces as they are |
interface or type?
The converter writes export interface by default and export type if you tick the option. For objects like these the two work the same way. Interfaces can be extended and merged; type aliases can also describe unions such as User[] or string | number, which is why the converter uses a type for the array at the root (UserList).
One more thing the sample showed: money as floats
The test summed the order with qty * price - discount and got 29.490000000000002, not 29.49. JSON numbers become JavaScript floating-point numbers, and decimal amounts don't add up exactly. For prices, have the API send whole cents (1250) or a string, and format only for display.
FAQ
Can I generate TypeScript types from JSON in VS Code?
Extensions can do it, and so can the browser-based converter. Whichever you use, check the output for the cases in step 2.
How do I make every field optional?
Wrap the type: Partial<Order>. Use it for update payloads, not for responses, or you lose the checks you wanted.
Should dates be typed as Date?
Not in the type for the raw JSON, because JSON can only carry the string. Convert after parsing, or let Zod do it with z.coerce.date(), and give the converted object its own type.
Is my JSON uploaded when I use the converter?
No. It runs in your browser; nothing is sent to a server.
My JSON won't convert. Why?
It is probably not valid JSON: trailing commas, single quotes and comments are the usual causes. See common JSON syntax errors or check it in the JSON formatter first.