← Back to TypeScript Course | Chapter 15: TypeScript with APIs | Lesson 3 of 6

Typing API Responses

Typing an API response means describing the structure of data returned by a server. Response types make properties predictable and help TypeScript catch incorrect property access during development.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.