JSON to TypeScript: Convert API Responses to Types

September 28, 2026  |  9 min read  |  TypeScript

By Syed · Frontend Engineer & Creator of UITweak

Every frontend developer knows this workflow: you call an API, get back a JSON blob, and then hand-write TypeScript interfaces field by field, hoping you did not miss a nested object or mistype a key. It is slow, boring, and error prone. This guide shows you how to convert JSON to TypeScript types systematically, what to watch out for, and how to handle the tricky cases like nested arrays, nullable fields, and unions.

Shortcut: paste any JSON into our free JSON to TypeScript converter and get clean interfaces instantly, plus 15 more output languages.

1. The Basic Conversion Pattern

The core idea is simple: every JSON object becomes an interface, every key becomes a property, and every value becomes a type. Take this typical API response:

{
  "id": 42,
  "username": "tanzil_dev",
  "isActive": true,
  "score": 98.5
}

It converts to:

interface User {
  id: number;
  username: string;
  isActive: boolean;
  score: number;
}

JSON has only a few primitive types, so the mapping is mechanical: strings to string, numbers to number (TypeScript does not distinguish int from float), booleans to boolean, and null needs a decision (see section 5).

2. Nested Objects Become Nested Interfaces

Real API responses are nested. Each nested object gets its own interface, which keeps things readable and reusable:

// JSON
{
  "id": 42,
  "profile": {
    "firstName": "Syed",
    "address": {
      "city": "Dubai",
      "country": "UAE"
    }
  }
}

// TypeScript
interface Address {
  city: string;
  country: string;
}

interface Profile {
  firstName: string;
  address: Address;
}

interface User {
  id: number;
  profile: Profile;
}

Tip: name interfaces after what they represent (Address, not AddressObject). If the same nested shape appears in multiple responses, you define it once and reuse it.

3. Arrays: Look at the First Element (Then Verify)

A JSON array maps to Type[]. The catch: you must decide the element type from the data, and one sample is not always enough:

// JSON
{ "tags": ["css", "tailwind"], "scores": [10, 20] }

// TypeScript
interface Post {
  tags: string[];
  scores: number[];
}

// Array of objects: define the element interface
interface OrderItem {
  sku: string;
  qty: number;
}
interface Order {
  items: OrderItem[];
}

Watch out: if an array is empty ([]) in your sample, its element type is unknowable. Mark it unknown[] temporarily and fix it once you see real data, rather than guessing any[].

4. Optional Fields: The ? Modifier

APIs often omit keys instead of sending null. If a field is sometimes missing, mark it optional:

interface User {
  id: number;
  username: string;
  bio?: string;        // sometimes missing
  avatarUrl?: string;  // sometimes missing
}

Rule of thumb: if you have seen the response both with and without the key, use ?. If the API always sends the key but sometimes with a null value, that is a different case (next section).

5. Null Values: Decide, Do Not Ignore

JSON null is the biggest source of runtime crashes in typed code. You have three honest options:

  • field: string | null : the API explicitly sends null. Handle both cases in your code.
  • field?: string : the key is sometimes absent entirely.
  • field?: string | null : both happen (common with third-party APIs). Ugly but honest.

Never silently type a nullable field as string. TypeScript will believe you, and your app will crash the first time null arrives.

6. Unions for Fields With Multiple Shapes

Sometimes one field holds different types. A status might be a string, or an event payload might be one of several shapes:

interface ApiResponse {
  status: "ok" | "error" | "pending";  // string literal union
  data: UserData | ErrorData;          // discriminated union
}

interface UserData {
  kind: "user";
  user: User;
}
interface ErrorData {
  kind: "error";
  message: string;
}

The kind field is called a discriminant. It lets TypeScript narrow the type in if statements, so you get autocomplete for the correct shape in each branch.

7. Utility Types for API Work

Once you have base interfaces, TypeScript's utility types save a lot of duplication:

// Partial: for PATCH request bodies where every field is optional
type UserUpdate = Partial<User>;

// Pick: for list views that only need a few fields
type UserCard = Pick<User, "id" | "username">;

// Omit: strip sensitive fields before sending to the client
type PublicUser = Omit<User, "passwordHash">;

// Record: for dictionaries / maps in responses
type Translations = Record<string, string>; // { "en": "Hello", "fr": "Bonjour" }

8. Common Gotchas

  • Dates are strings. JSON has no date type. "2026-09-29T10:00:00Z" is a string until you parse it. Type it as string and convert explicitly.
  • Numbers that are really IDs. If an API sends "id": "42" as a string, keep it string. Do not "fix" it to number, or comparisons will break.
  • Avoid any. Every any is a hole in your type safety. Prefer unknown and narrow it when you must handle dynamic data.
  • One sample is not a schema. Paginate, trigger errors, and check edge cases. The happiest-path response hides the nullable fields.

Skip the hand-writing entirely

Paste any JSON and get TypeScript interfaces instantly, with tree view, diffing, smart fixing for broken JSON, and 15 more output languages from Python to Go to SQL.

Open the JSON converter, it's free

# Expansion draft: json-to-typescript-guide

Your Interfaces Vanish at Runtime

TypeScript interfaces are compile-time only. After tsc runs, every interface is gone, and the emitted JavaScript has no memory of the shapes you declared. That surprises people because the code looks like a guarantee:

interface User {
  id: number;
  username: string;
}

async function getUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  return res.json(); // Promise<any> wearing a User costume
}

res.json() returns Promise<any>. The Promise<User> annotation is a promise you made to the compiler, not a check the runtime performs. If the API starts returning username: null or renames id to userId, TypeScript says nothing and your app breaks at the line you trusted most. Interfaces describe what you hope the data looks like. They never verify it.

Pairing Interfaces With Zod at API Boundaries

The practical answer: derive your types from a runtime schema instead of writing them by hand. Zod's z.infer gives you the TypeScript type from the schema, so one definition serves both worlds:

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  username: z.string(),
});

type User = z.infer<typeof UserSchema>;

async function getUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  const json: unknown = await res.json();
  return UserSchema.parse(json); // throws on bad data, returns a real User
}

Notice json: unknown: assigning the any from res.json() to unknown forces the schema to do the proving. parse throws on mismatch, so bad data fails loudly at the boundary instead of silently three components deep. The type User line stays in sync forever because it is derived, not duplicated. Static types only? The main guide's interface workflow is fine. Data crossing a network? I want the schema.

Discriminated Unions: The Exhaustiveness Check

The main guide shows the kind discriminant. What converters skip is the fourth variant the API adds six months later. Without a guard, your switch falls through and returns undefined from a function typed to return a number. The fix is the never exhaustiveness check:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle":
      return Math.PI * s.radius ** 2;
    case "square":
      return s.side * s.side;
    default: {
      const _exhaustive: never = s;
      throw new Error(`Unhandled shape: ${JSON.stringify(s)}`);
    }
  }
}

Handle every case and s narrows to never in the default branch, so the assignment compiles. Add a "triangle" variant later and it stops compiling, pointing at the exact function to update. I put this check in every switch over API-provided unions. It turns "the API added a variant" from a production incident into a compile error.

Dictionary Maps: Beyond Record<string, string>

The main guide's Record<string, string> covers string-to-string maps, but real APIs send maps with structured values and often a known set of keys. Type the values honestly and constrain the keys when you can:

// Values with structure, not just strings
type PricesBySku = Record<string, { amount: number; currency: string }>;

// Known key set: a typo'd locale becomes a compile error
type Greeting = Record<"en" | "fr" | "de", string>;

// When keys are truly dynamic, an index signature reads better
interface FeatureFlags {
  [flagName: string]: boolean;
}

If the key set is finite and known, write it as a union. Record<string, ...> hides typos ("eng" instead of "en" compiles fine and fails at runtime). Index signatures and Record are interchangeable; I use Record for derived shapes and index signatures when the map itself is the named domain concept.

Pagination Wrappers With Generics

Nearly every list endpoint wraps its items in the same envelope: the page of data plus metadata about where you are in the whole set. Typing each endpoint's wrapper separately duplicates the envelope a dozen times. One generic covers all of them:

interface PaginatedResponse<T> {
  data: T[];
  page: number;
  pageSize: number;
  total: number;
  hasMore: boolean;
}

type UserPage = PaginatedResponse<User>;
type OrderPage = PaginatedResponse<OrderItem>;

Two details make this work. First, name the item field after what your API actually sends (data, items, results) and stick with it. Second, keep metadata fields required unless the API genuinely omits them. I have seen hasMore typed optional "just in case," forcing a null check into every infinite-scroll handler for a field the API always sends. Type what the API does, not what it might do.

Branded Types for IDs

APIs hand you a dozen string IDs: user ids, order ids, session tokens. TypeScript sees string for all of them, so nothing stops you passing an OrderId where a UserId belongs. Branded types add a compile-time tag the runtime never sees:

type Brand<T, Tag extends string> = T & { readonly __brand: Tag };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;

function getUser(id: UserId) {
  /* ... */
}

const orderId = "ord-9" as OrderId;
getUser(orderId); // error: OrderId is not assignable to UserId

The brand is type-system only. At runtime these are plain strings: zero overhead, no serialization concern. The as UserId cast happens once, where the raw string enters your code, and from there the compiler tracks which id is which. I brand IDs in any codebase with more than two entity types. The first time it catches a swapped argument, it pays for itself.

JSON.parse Gives You any

JSON.parse returns any. Not unknown, not a parameterizable generic. Every property access on the result is unchecked, which quietly defeats the interfaces you just wrote:

const data = JSON.parse(text); // data: any
const user = data as User;     // compiles regardless of what text contains

The as User cast is you asserting, not the compiler verifying. My habit: annotate the parse result unknown immediately, then narrow with a Zod schema or explicit checks. const data: unknown = JSON.parse(text) costs nothing and turns every property access into a compile error until you prove the shape. Treat JSON.parse output like form input: untrusted until validated.

BigInt Precision Loss and the Date Reviver

Two JSON.parse behaviors surprise experienced developers. First, numbers beyond Number.MAX_SAFE_INTEGER lose precision silently: JSON.parse('{"id": 9007199254740993}') gives you 9007199254740992, a different id, with no error. If your API uses 64-bit integer ids, agree on string ids with the backend. Typing the field number does not protect you; the damage happens inside the parser.

Second, ISO-8601 dates come back as strings and stay strings. "2026-10-21T10:00:00Z" is a string until you convert it, as the main guide's gotcha says. For payloads full of dates, the reviver parameter converts them in one pass:

const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;

const data = JSON.parse(text, (key, value) =>
  typeof value === "string" && isoDate.test(value) ? new Date(value) : value
);

The reviver runs bottom-up on every value, so nested dates convert too. Keep the regex tight: a loose pattern will "convert" date-ish strings like product SKUs. Reviver-converted fields are Date in your interface, not string.

Share this guide