Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 96 ยท TypeScript in Practice

Typing APIs and JSON Data

Model API responses in TypeScript, validate unknown JSON at runtime, infer types from schemas like Zod, generate types from OpenAPI and build a generic, type-safe fetch wrapper.

TypeScript checks your code, but it can't check the outside world. The moment data arrives from an HTTP API, a file, localStorage or a message queue, the compiler has no idea what's inside. JSON.parse() returns any, response.json() returns any (or unknown, depending on your types), and a single wrong assumption can travel deep into your app before it explodes.

This lesson is about that boundary. You'll model API data with types, see why a type alone is only a promise, validate unknown data at runtime, let a schema produce both the validator and the type, generate types from an API description, and wrap fetch in a small generic client that is type-safe from URL to result.

The examples are runnable. Our editor has no network access, so they use data: URLs (which Node's fetch can read) and a simulated server built with the standard Response class. The code is the same as it would be against a real API.

Modelling API data

Start by writing down what the API sends. Interfaces describe resources, and generics describe the wrappers that APIs put around them, like pagination envelopes:

TypeScript
interface User {
  id: number;
  email: string;
  name: string;
  avatarUrl: string | null; // the API sends null when there is no avatar
  createdAt: string;        // JSON has no Date type: dates arrive as ISO strings
  role: 'admin' | 'member';
}

interface Page<T> {
  items: T[];
  page: number;
  totalPages: number;
}

type UserPage = Page<User>;

A few modelling rules save a lot of pain later:

  • Model the wire format honestly. If the API sends null, write | null; if a field can be missing, make it optional (?). Don't type dates as Date, because JSON.parse never creates Date objects.
  • Use literal unions for fields with a fixed set of values ('admin' | 'member'), so narrowing and exhaustiveness checks work.
  • Separate the wire type from your domain type when they differ. Convert once, at the boundary, and the rest of your app works with clean data.
TypeScript Converting a wire type into a domain type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
{
  id: 1,
  name: 'Ada',
  avatarUrl: undefined,
  createdAt: 2026-03-14T09:30:00.000Z,
  isAdmin: true
}
2026 true

The snake_case names, the null and the date string stay at the edge. Everything after toUser() gets camelCase, undefined and a real Date.

A type is only a promise

Here's the trap. The data comes from JSON.parse, which returns any, so you can assign it to anything:

TypeScript any lets bad data through (crashes at runtime)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It compiles without a single error, then fails when it runs (the stack trace below the error points at main.ts:12):

TEXT
string
TypeError: product.price.toFixed is not a function

The annotation Product was a promise nobody checked. TypeScript trusted any, and the actual price was a string. In a real app, the crash would happen far from the JSON.parse call, in a component or a report, where nobody would think to look at the API.

The fix starts with one word: assign outside data to unknown instead (see any, unknown, never and void). With unknown, the compiler refuses to let you use the value until you've checked it:

TypeScript
const data: unknown = JSON.parse(body);
data.price;
// error TS18046: 'data' is of type 'unknown'.

Validating unknown data

To go from unknown to Product, you check the shape at runtime. A type guard does that and tells the compiler about it:

TypeScript
function isProduct(value: unknown): value is Product {
  return (
    typeof value === 'object' && value !== null &&
    'name' in value && typeof value.name === 'string' &&
    'price' in value && typeof value.price === 'number'
  );
}

That works, but for real APIs with dozens of types, hand-written guards get long, and nothing guarantees that a guard matches its interface: add a field to Product and forget the guard, and the compiler stays quiet.

The modern answer is to write a schema once and derive both the runtime validator and the static type from it. Libraries like Zod and Valibot do exactly that. To see how they work inside, here is a tiny schema library in about 40 lines:

TypeScript A tiny schema library with type inference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
OK: Lamp costs 19.99
Rejected: value.price must be a number
Rejected: value.tags[1] must be a string

The second body has a string price, and the third has the number 7 where every tag must be a string. Notice how each message points at the exact path of the problem (value.tags[1]). Precise, path-based errors are one of the biggest benefits of schema validation.

The interesting part is the types. Infer<typeof ProductSchema> uses a conditional type with infer to pull T out of Schema<T>, and object() builds its result type with a mapped type over the shape. Change the schema, and Product changes with it. They can never drift apart.

(The two as casts inside object() are the price of building an object key by key. They're safe because each value was just checked; a library hides them from you.)

Zod and other schema libraries

In real projects you'd use a well-tested library. Zod is the most popular; this is what the same product schema looks like with it:

TypeScript
import { z } from 'zod';

const Product = z.object({
  name: z.string().min(1),
  price: z.number().positive(),
  tags: z.array(z.string()).default([]),
  discount: z.number().min(0).max(1).optional(),
});

type Product = z.infer<typeof Product>;

const result = Product.safeParse(await response.json());
if (!result.success) {
  console.error(result.error.issues); // detailed, path-based issues
} else {
  console.log(result.data.price);     // fully typed
}
  • parse() throws on invalid data; safeParse() returns a discriminated union you check with success.
  • Schemas can do more than types can: minimum lengths, positive numbers, email formats, defaults and transformations (for example z.coerce.date() turns an ISO string into a Date).
  • Valibot offers a similar API split into small functions, so bundlers can drop what you don't use; ArkType uses TypeScript-like string syntax. All of them follow the "schema first, type inferred" idea.

Validate at the boundary, once: right where data enters your program (an API response, a form submission, a config file, a message from another service). Inside your app, trust the types. Validating the same object again and again in every function is a sign the boundary isn't clear.

Generating types from an API description

If the API is described by an OpenAPI (Swagger) document, you don't have to write the types by hand. Tools read the description and generate TypeScript:

Terminal
npx openapi-typescript https://api.example.com/openapi.json -o src/api-types.ts

The generated file contains a paths type that describes every endpoint, which typed clients such as openapi-fetch use directly:

TypeScript
import type { paths } from './api-types';

type GetUserResponse =
  paths['/users/{id}']['get']['responses'][200]['content']['application/json'];

Other ecosystems have the same idea: GraphQL Code Generator produces types from a GraphQL schema and your queries, and tRPC shares types between a TypeScript server and client without any generation step. Generated types still describe what the server promises; for APIs you don't control, combine them with runtime validation (some generators can emit Zod schemas too).

A generic, type-safe fetch wrapper

A common mistake is a "typed" fetch helper that is really a cast:

TypeScript
// Looks safe, is not: T is whatever the caller says, nothing is checked.
async function getJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  return response.json() as Promise<T>;
}

The fix is to make the caller pass a validator, and let the validator's type decide T. Combined with a Result type (see error handling), every failure becomes a value you must handle:

TypeScript getJson with a validator and a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints one success and two different failures:

TEXT
#1 Write lesson [x]
failed: invalid data: done must be a boolean
failed: invalid data: Unexpected token 'o', "not json" is not valid JSON

You never write getJson<Todo>(...): TypeScript infers T as Todo from the validator, so the type and the check always match. A Zod schema fits the same slot: pass (v) => Product.parse(v).

Describing a whole API with a type map

For an API with many endpoints, describe them all in one type and let a single generic function look up the right request and response types. This is the same technique behind typed clients like openapi-fetch. Here the "server" is a local function returning real Response objects:

TypeScript An endpoint map for a typed client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
created { id: 2, title: 'Neuromancer', year: 1984 }
Dune, Neuromancer
Neuromancer (1984)
GET /books/:id failed with 404

Everything the caller touches is typed: the route string must be a key of Api (a typo is an error), body must be Omit<Book, 'id'> for POST /books, and the result is Book[] or Book depending on the route, all through the indexed access type Api[R]['response']. The Typed API client project takes this further with route parameters checked by template literal types and runtime validation for every route.

The single as in request() is an honest, contained trust point: one line, documented, in one function. That's the goal. Not zero assertions, but one clearly marked place where outside data becomes typed data.

Request bodies: create and update types

APIs usually accept slightly different shapes for creating and updating than they return. Utility types derive them from the main type, so they stay in sync:

TypeScript
interface Article {
  id: string;
  title: string;
  body: string;
  tags: string[];
  publishedAt: string | null;
}

type CreateArticle = Omit<Article, 'id' | 'publishedAt'>;   // the server sets these
type UpdateArticle = Partial<CreateArticle>;                // PATCH: any subset
type ArticleSummary = Pick<Article, 'id' | 'title'>;        // list endpoints

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. const p: Product = JSON.parse(text); compiles. Why is this risky?

    any is assignable to every type, so the annotation is an unchecked promise. Assign to unknown and validate instead.
  2. 2. What is the main advantage of a schema library like Zod over hand-written interfaces plus type guards?

    With z.infer (or Infer in the lesson's mini library), the type is computed from the schema, so changing one changes the other.
  3. 3. What is wrong with async function getJson<T>(url: string): Promise<T> { return (await fetch(url)).json() as Promise<T>; }?

    Callers can write getJson<User>(url) and get a User type for any data. Taking a validator parameter lets the validator decide T.
  4. 4. Given interface Api { "GET /users": { response: User[] } }, what is Api["GET /users"]["response"]?

    An indexed access type looks up the property's type. This is how one generic request function can return the right type for each route.
  5. 5. Where should you validate data from an API?

    Validate once where untrusted data arrives and convert it into well-typed values. After that, the types can be trusted.

Summary

  • Model the wire format honestly (null, optional fields, dates as strings), and convert to domain types once, at the boundary.
  • JSON.parse and response.json() give you any (or unknown): a type annotation on them is an unchecked promise.
  • Treat outside data as unknown and validate it with type guards or, better, a schema whose type is inferred (Zod, Valibot or your own).
  • Generate types from OpenAPI or GraphQL when an API description exists, and still validate data you don't control.
  • Build fetch helpers that take a validator, so T is inferred from a real check, and return a Result for failures.
  • Describe many endpoints with one type map and look up request and response types with indexed access types.

Next: TypeScript with React