Typing API Responses
In this page:
Simple Response Interfaces
A simple response interface lists each field an API endpoint returns along with its type, giving you compile-time checking anywhere that response is consumed after being parsed.
Example: Simple Response Interfaces
interface UserResponse {
id: number;
name: string;
email: string;
}
const user: UserResponse = { id: 1, name: "Ravi", email: "[email protected]" };
console.log(user);
Nested API Responses
Nested API responses are typed by composing smaller interfaces — like a User interface used inside an Order interface's customer field — instead of flattening everything into one giant, hard-to-reuse type.
Example: Nested API Responses
interface User {
name: string;
}
interface Order {
id: number;
customer: User;
}
const order: Order = { id: 1, customer: { name: "Ravi" } };
console.log(order.customer.name);
Optional and Nullable Fields
Marking a field optional (?) or nullable (| null) in a response interface reflects what the API can genuinely omit or send as null, and skipping this distinction is a common source of runtime crashes on missing data.
Example: Optional and Nullable Fields
interface Profile {
bio?: string;
avatarUrl: string | null;
}
const profile: Profile = { avatarUrl: null };
console.log(profile);
Generic API Response Wrappers
A generic API response wrapper — like ApiResponse<T> holding a data: T field alongside status metadata — lets you reuse one envelope type across every endpoint instead of redefining a response shape's outer structure each time.
Example: Generic API Response Wrappers
interface ApiResponse<T> {
data: T;
status: number;
}
interface User { name: string; }
const response: ApiResponse<User> = { data: { name: "Ravi" }, status: 200 };
console.log(response.data.name);
Validating Runtime API Data
Because TypeScript's types disappear at runtime, validating that API data actually matches its declared interface (with a schema library or manual checks) is the only way to catch a backend sending an unexpected shape.
Example: Validating Runtime API Data
interface User { name: string; }
function isUser(value: any): value is User {
return typeof value?.name === "string";
}
const raw: any = { name: "Ravi" };
if (isUser(raw)) console.log(raw.name);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: