JSON to TypeScript: interfaces, types and Zod

A TypeScript type describes JSON only at compile time. This guide covers how to write types that match real payloads, and how to check them at runtime.

3 min readUpdated MasterDev

Interface or type alias

Generated by the json.foo converter
export interface User {
  id: number;
  "full-name": string;
  address: Address;
  orders: Order[];
}

export interface Order {
  sku: string;
  qty: number;
  note?: string;
}

For the shape of a JSON object, interface and type are interchangeable. Interfaces can be extended and merged; type aliases can also describe unions such as "paid" | "pending". Pick one for your codebase and stay with it. The converter's Declaration option writes either.

Optional is not the same as null

APIs use both, and they mean different things:

note?: string
The key may be missing. When present, it holds a string.
note: string | null
The key is always there, but its value may be null.
note?: string | null
Both: missing, null or a string.

The converter follows your sample: a key missing from some items gets ?, a key that is null in some items gets | null. These only protect you with strict (or at least strictNullChecks) on in tsconfig.json.

unknown, not any

When a key is null in every item, or holds different types, the converter writes unknown. Unlike any, unknown makes you check the value before you use it, so a wrong guess shows up as a compile error and not as a crash in production. Replace it with the real type once you know it.

Numbers and dates

JSON has one number type and so does TypeScript: number covers both 3 and 3.5. JSON.parse never produces a bigint, so large IDs lose precision unless the API sends them as strings.

Dates arrive as strings. Type them as string, not Date: the compiler would accept Date, but at runtime you would still have a string and calls like .getTime() would fail. Convert with new Date(value) where the data enters your app, or let Zod do it (see below).

The problem with casting

const user = (await res.json()) as User;

res.json() returns Promise<any>, and as User asks the compiler to trust you. If the API renames a field tomorrow, nothing complains here; the error surfaces somewhere else, as undefined, far from its cause. Types describe what you expect. To know what you received, validate.

Validating with Zod

Set Declaration to Zod schema in the converter and you get schemas plus types derived from them, so there is one source of truth:

Generated by the json.foo converter
import { z } from "zod";

export const Order = z.object({
  sku: z.string(),
  qty: z.number().int(),
  note: z.string().optional(),
});
export type Order = z.infer<typeof Order>;
const order = Order.parse(await res.json()); // throws a ZodError with the failing path

const result = Order.safeParse(data);         // or check without throwing
if (!result.success) console.error(result.error.issues);

By default Zod drops keys the schema does not list, so extra fields from the API never leak into your app. For dates, change z.string() to z.coerce.date() and the parsed value is a real Date.

readonly and export

The Readonly option marks every property readonly, which stops code from changing API data in place. It is shallow: arrays inside stay mutable unless typed as readonly Order[]. Export adds export to each declaration so you can import them from other files.

A workflow that holds up

  1. Copy a real response from your browser's network tab and check it in the formatter.
  2. Generate a Zod schema in the converter.
  3. Tighten it: enums with z.enum([...]), dates with z.coerce.date(), real types instead of unknown.
  4. Parse every response at the edge of your app, and use the inferred types everywhere else.