JSON Converter · Tutorial

How to add TypeScript types to an API response

7 min readbeginnerUpdated

Your front end calls a user API and the response is typed as any, so typos in field names go unnoticed. This tutorial generates interfaces from a real response, explains each part of the output and refines it so TypeScript can catch mistakes in your code.

What you need

  • The JSON Converter with TypeScript chosen under Convert to
  • A sample response from your API, or the user profile from the Try it button

Steps

  1. Copy a real response

    Open your browser's developer tools, find the API request in the Network panel, and copy the response body. Paste it into the left box. The sample is a user profile with settings, roles and team memberships.

  2. Name the root type

    Type User in Root type name. The right box now starts with export interface User, and nested objects got their own interfaces: Settings, Notifications and Team.

  3. Read the optional fields

    In the teams array, only the second team has joinedAt. The generator compared both items, so Team has joinedAt?: string. TypeScript will now remind you to handle teams without that date.

  4. Fix the unknown type

    avatarUrl was null in the sample, so its type is unknown. You know it holds a URL when it is set, so change it to avatarUrl: string | null;.

  5. Narrow strings to known values

    role can only be owner or member. Replace role: string; with a union. Now a typo like 'onwer' becomes a compile error.

    export interface Team {
      id: number;
      name: string;
      role: 'owner' | 'member';
      joinedAt?: string;
    }
  6. Use the types in your fetch code

    Download types.ts, add it to your project, and annotate the result: const user = (await res.json()) as User;. Your editor now autocompletes user.settings.theme and flags misspelt fields.

Try it yourself

Opens the JSON Converter with this tutorial's sample loaded.

Try it now

Common mistakes

Generating from an error response
If you copy a 401 or 500 response, you get types for the error body. Make sure the request succeeded before copying.
Treating the cast as validation
as User only tells the compiler what to expect; it doesn't check the data. Use a Zod schema (choose Zod in the same JSON Converter) when the response must be verified at runtime.
One sample for a list endpoint
Paste several items from a list response so optional fields are detected. A single item makes every field look required.

Next steps

Go back to the JSON Converter, or keep going with one of these:

FAQ

Can I make every field optional for a PATCH request?

Yes. Tick Make every field optional, or use TypeScript's Partial<User> on the generated type.

What if the response is an array?

You get an interface for one item plus a list type, such as export type UserList = User[].