0
0
Typescriptprogramming~5 mins

Type-safe API response handling in Typescript

Choose your learning style9 modes available
Introduction

Type-safe API response handling helps you catch mistakes early by making sure the data you get from an API matches what you expect. This keeps your program safe and easier to fix.

When you call an API and want to be sure the data has the right shape before using it.
When you want to avoid bugs caused by unexpected or missing data from a server.
When working in a team and you want clear rules about what data your functions expect.
When you want your code editor to help you with suggestions and errors based on the API data.
When you want to handle errors gracefully if the API response is not what you expected.
Syntax
Typescript
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('Network error');
  }
  const json = await response.json();
  return json as ApiResponse<T>;
}

Use interface or type to define the expected shape of the API response.

Use generics <T> to make the function flexible for different data types.

Examples
This example shows how to type the API response when expecting a User object.
Typescript
interface User {
  id: number;
  name: string;
}

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

async function fetchUser(): Promise<ApiResponse<User>> {
  const response = await fetch('https://api.example.com/user');
  if (!response.ok) {
    throw new Error('Network error');
  }
  const json = await response.json();
  return json as ApiResponse<User>;
}
This example types the response for a Product object from the API.
Typescript
interface Product {
  id: number;
  title: string;
  price: number;
}

async function fetchProduct(): Promise<ApiResponse<Product>> {
  const response = await fetch('https://api.example.com/product');
  if (!response.ok) {
    throw new Error('Network error');
  }
  const json = await response.json();
  return json as ApiResponse<Product>;
}
This version adds a simple check for network errors before parsing the JSON.
Typescript
async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('Network error');
  }
  const json = await response.json();
  return json as ApiResponse<T>;
}
Sample Program

This program fetches a user from a public API and uses a type-safe response structure. It prints the status, message, and user details if successful, or an error message if something goes wrong.

Typescript
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

interface User {
  id: number;
  name: string;
}

async function fetchUser(): Promise<ApiResponse<User>> {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
  if (!response.ok) {
    throw new Error('Failed to fetch user');
  }
  const userData = await response.json();
  return {
    data: { id: userData.id, name: userData.name },
    status: response.status,
    message: 'User fetched successfully'
  };
}

fetchUser()
  .then(result => {
    console.log(`Status: ${result.status}`);
    console.log(`Message: ${result.message}`);
    console.log(`User ID: ${result.data.id}`);
    console.log(`User Name: ${result.data.name}`);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });
OutputSuccess
Important Notes

Always check if the network response is okay before using the data.

Type assertions like as ApiResponse<T> tell TypeScript what to expect but do not check data at runtime.

For full safety, consider validating the data shape at runtime using libraries like zod or io-ts.

Summary

Type-safe API response handling helps catch errors early by defining expected data shapes.

Use TypeScript interfaces and generics to describe API responses clearly.

Always handle possible errors like network failures or unexpected data.