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
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.
Name the root type
Type
Userin Root type name. The right box now starts withexport interface User, and nested objects got their own interfaces:Settings,NotificationsandTeam.Read the optional fields
In the
teamsarray, only the second team hasjoinedAt. The generator compared both items, soTeamhasjoinedAt?: string. TypeScript will now remind you to handle teams without that date.Fix the unknown type
avatarUrlwasnullin the sample, so its type isunknown. You know it holds a URL when it is set, so change it toavatarUrl: string | null;.Narrow strings to known values
rolecan only beownerormember. Replacerole: 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; }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 autocompletesuser.settings.themeand flags misspelt fields.
Try it yourself
Opens the JSON Converter with this tutorial's sample loaded.
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 Useronly 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[].