JSON to TypeScript: Typing API Responses Properly
When building modern web applications, you almost always interact with JSON APIs. In the JavaScript era, we simply parsed the JSON and hoped the structure matched our expectations. In the TypeScript era, that's not good enough.
Typing your API responses is the single most important step for maintaining a robust, scalable codebase. Let's look at the best practices for converting JSON to TypeScript interfaces.
The Problem with any
The native fetch API in TypeScript returns a Promise containing a Response object. When you call await res.json(), the return type is any.
const res = await fetch("https://api.example.com/user/1");
const data = await res.json(); // data is 'any'
// TypeScript won't catch this error!
console.log(data.usename); This completely defeats the purpose of using TypeScript.
Best Practice 1: Define Interfaces for Everything
Whenever you hit an API endpoint, you should have a pre-defined Interface representing exactly what you expect to receive.
interface User {
id: number;
username: string;
email: string;
isActive: boolean;
createdAt: string;
}
const res = await fetch("https://api.example.com/user/1");
const data = (await res.json()) as User;
console.log(data.username); // Type-safe!Best Practice 2: Handle Nullable Fields
APIs are messy. A common mistake developers make when writing TypeScript interfaces is assuming every field will always be present and populated.
interface User {
id: number;
companyId: string;
}interface User {
id: number;
companyId: string | null;
// or companyId?: string;
}Always check API documentation to see which fields are nullable or optional. Use | null for fields that return null, and ?: for fields that might be omitted from the JSON entirely.
Best Practice 3: Automate the Conversion
Writing interfaces by hand for massive JSON responses (like from Stripe or GitHub's API) is incredibly tedious and prone to human error.
Generate TypeScript from JSON
Don't waste time typing out nested interfaces manually. Paste your raw JSON response into our generator, and we'll instantly build the perfect TypeScript interfaces for you.
Open JSON to TypeScript Converter