Skip to content
Esc
  • MQTT Topic MatcherTest MQTT topic filters with + and # wildcards against topics, and check ACL patterns.
  • JSON FormatterBeautify, minify and validate JSON instantly as you type.
  • JSON DiffCompare two JSON documents and see every added, removed and changed value by path.
  • JSON to TypeScriptGenerate TypeScript interfaces or Zod schemas from a sample JSON response.
  • Base64 Encoder/DecoderConvert text to Base64 and back, with full Unicode support.
  • UUID GeneratorGenerate random v4 UUIDs — one or many — in the format you need.
  • JWT DecoderDecode JSON Web Tokens to inspect the header, payload and expiry.
  • Timestamp ConverterConvert Unix timestamps to dates and dates to timestamps.
  • URL Encoder/DecoderPercent-encode and decode URLs, and break down query strings.
  • Hash GeneratorGenerate MD5, SHA-1, SHA-256 and SHA-512 hashes of text or files.
  • Regex TesterTest regular expressions with live match highlighting and groups.
  • YAML to JSON ConverterConvert YAML to JSON and JSON to YAML, with clear error locations.
  • SQL FormatterBeautify or minify SQL for PostgreSQL, MySQL, SQL Server and 9 more dialects.
  • Mock Data GeneratorGenerate realistic fake data for API mocks as JSON, CSV or SQL inserts.
  • HTTP Header AnalyzerGrade response headers: CSP, HSTS, cookies, CORS and caching, explained.
  • Webhook Signature VerifierVerify and generate webhook signatures for GitHub, Stripe, Slack, Shopify and more.
  • Cron Expression GeneratorBuild and explain cron schedules, with the next run times in any time zone.
  • .env File ValidatorFind syntax errors, duplicates and missing keys in .env files.
  • HTML to JSX ConverterConvert HTML to valid React JSX: className, style objects, self-closing tags.
  • SVG to React ComponentTurn SVG files into React icon components with props and currentColor.
  • Markdown EditorWrite Markdown with a live preview, GitHub tables and task lists, and HTML export.

↑ ↓ to moveEnter to openPaste data to open it in the right tool. Nothing leaves your browser.

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, crashes

With 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 valueTypeScript typeExample
stringstring"ada@example.com"
numbernumber49.5
true / falsebooleantrue
nullnull (in a union)string | null
objectan interfaceaddress: Address
arrayT[]roles: string[]
array of mixed valuesunion 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:

DeclarationKey missingKey is nullUse when
couponCode?: stringallowedtype errorthe API leaves the key out
avatarUrl: string | nulltype errorallowedthe key is always sent, sometimes as null
nickname?: string | nullallowedallowedboth 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 checked

For 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 wrong

Common mistakes

  • Typing a field as null because it was null in the sample. Use the real type, such as string | 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, so createdAt arrives as a string until you parse it.
  • Typing large IDs as number. Integers above 2^53 lose precision in JSON.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 every switch and 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.