Guide
How to convert JSON to TypeScript interfaces
await res.json() gives you any, so TypeScript can't catch a typo in a field name or a missing null check. Describing the response with interfaces fixes that — if the interfaces match what the API really sends.
Updated · 3 min read
The problem
const res = await fetch("/api/users/1042");
const user = await res.json(); // any
user.emial.toLowerCase(); // typo — compiles, crashes at runtime
user.avatarUrl.startsWith("https"); // avatarUrl can be null — compiles, crashesWith an interface for the response, both lines become compile-time errors, and your editor autocompletes every field.
Step 1: Get a representative sample
Types inferred from one response only describe that response. Before you start, collect a sample that shows the variety the API really returns:
- For list endpoints, take several items, including one with every optional field filled in.
- Include a record where nullable fields are actually
null, and one where they have values. - Check the API documentation or OpenAPI spec for fields that are only sent in some cases.
Step 2: Map each JSON type to TypeScript
| JSON value | TypeScript type | Example |
|---|---|---|
| string | string | "ada@example.com" |
| number | number | 49.5 |
| true / false | boolean | true |
| null | null (in a union) | string | null |
| object | an interface | address: Address |
| array | T[] | roles: string[] |
| array of mixed values | union array | (string | number)[] |
Each nested object gets its own named interface. That keeps the types readable and lets you reuse them — the same Address might appear as both shippingAddress and billingAddress.
Step 3: Write the interfaces
Given this response:
{
"id": 1042,
"email": "ada@example.com",
"avatarUrl": null,
"roles": ["admin", "dev"],
"address": { "city": "London", "postcode": "N1 9GU" },
"orders": [
{ "id": "ord_1", "total": 49.5, "status": "paid" },
{ "id": "ord_2", "total": 12, "status": "refunded", "couponCode": "WELCOME" }
]
}the interfaces are:
export interface User {
id: number;
email: string;
avatarUrl: string | null;
roles: string[];
address: Address;
orders: Order[];
}
export interface Address {
city: string;
postcode: string;
}
export interface Order {
id: string;
total: number;
status: "paid" | "refunded";
couponCode?: string;
}Three decisions here came from knowledge, not from the sample: avatarUrl is string | null (the sample only showed null), status is a union of known values rather than string, and couponCode is optional because it appears in only one order.
Step 4: Optional or nullable?
These look similar but mean different things, and mixing them up is the most common typing bug:
| Declaration | Key missing | Key is null | Use when |
|---|---|---|---|
| couponCode?: string | allowed | type error | the API leaves the key out |
| avatarUrl: string | null | type error | allowed | the key is always sent, sometimes as null |
| nickname?: string | null | allowed | allowed | both happen |
Step 5: Use the types — and validate at the edges
Annotating the result tells the compiler what to expect, but nothing checks that the server actually sent it:
const user: User = await res.json(); // trusted, not checkedFor data you don't control — third-party APIs, webhooks, anything a client sends you — validate at runtime. A Zod schema does the check and gives you the type from one definition:
import { z } from "zod";
const userSchema = z.object({
id: z.number(),
email: z.string(),
avatarUrl: z.string().nullable(),
roles: z.array(z.string()),
});
type User = z.infer<typeof userSchema>;
const user = userSchema.parse(await res.json()); // throws if the shape is wrongCommon mistakes
- Typing a field as
nullbecause it was null in the sample. Use the real type, such asstring | null. - Making every property optional “to be safe”. You lose the checks you wanted, and every access needs a guard. Only mark what can really be missing.
- Typing dates as
Date. JSON has no date type, socreatedAtarrives as astringuntil you parse it. - Typing large IDs as
number. Integers above 2^53 lose precision inJSON.parse; if an API sends them as strings, keep them as strings. - Leaving status-like fields as
string. A union such as"paid" | "refunded"makes the compiler check everyswitchand comparison. - Assuming a cast or annotation validates anything. It doesn't — use a schema validator where the data comes from outside your code.
Generate the first draft automatically
The JSON to TypeScript tool does steps 2 and 3 for you: paste a sample, and it generates named interfaces (or a Zod schema), merges array items to find optional fields, and lists fields that were always null so you can type them properly. Then refine the result with what you know about the API, as in step 3.
Try the free JSON to TypeScript
Generate TypeScript interfaces or Zod schemas from a sample JSON response. Runs in your browser — nothing is uploaded.