If you're on a free Medium plan, click here to read — Free Access

Step 1: Define an Interface for the API Response

Interfaces in TypeScript are used to define the shape of objects, making them ideal for specifying the expected structure of API responses. Let's assume you are working with an API that returns a list of User objects. Each user has properties like id, name, and email.

Example Interface

Define an interface that matches the structure of the expected response data:

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

This User interface specifies that each object in the API response array must contain:

  • an id (number),
  • a name (string), and
  • an email (string).

Now that we have a User interface, let's define an array of users as our mock API response data.

Mock API Response

const apiResponse: User[] = [
  { id: 1, name: "Alice", email: "alice@example.com" },
  { id: 2, name: "Bob", email: "bob@example.com" },
  { id: 3, name: "Charlie", email: "charlie@example.com" }
];

Here, apiResponse is an array of objects, each adhering to the User interface.

Step 2: Loop Through the API Response

Once we have our User array, we can use different looping methods to iterate through the data. TypeScript offers several ways to loop through arrays, each suited for different use cases. Let's explore a few common approaches.

Using for...of Loop

The for...of loop is a simple and effective way to iterate through an array in TypeScript. It provides access to each item in the array directly.

Example with for...of Loop

for (const user of apiResponse) {
  console.log(`ID: ${user.id}, Name: ${user.name}, Email: ${user.email}`);
}

In this example:

  • Each user is typed as User, allowing you to access id, name, and email with full TypeScript type-checking.
  • This loop is ideal for accessing each item individually without needing the index.

Using forEach Method

The forEach method iterates over each element in the array, making it easy to perform operations on each item. It's particularly useful when you want to apply a function to each item.

Example with forEach

apiResponse.forEach((user) => {
  console.log(`ID: ${user.id}, Name: ${user.name}, Email: ${user.email}`);
});

Here:

  • forEach provides each user as a User object, letting you access properties directly.
  • TypeScript's type inference ensures that user has the correct type, making it easy to catch errors during development.

Using map Method

If you want to transform each item in the array, map is a great choice. It allows you to process each item and return a new array based on the results.

Example with map

Suppose you want to extract just the name property of each User:

const userNames = apiResponse.map((user) => user.name);
console.log(userNames); // Output: ["Alice", "Bob", "Charlie"]

In this example:

  • map iterates over apiResponse, retrieving each user's name property and storing it in a new array.
  • The result, userNames, is an array of strings containing just the names.

Using for Loop with Index

The traditional for loop with an index is also available in TypeScript. While less commonly used for straightforward array iteration, it can be helpful when you need access to the index of each element.

Example with for Loop

for (let i = 0; i < apiResponse.length; i++) {
  const user = apiResponse[i];
  console.log(`User ${i + 1}: ID: ${user.id}, Name: ${user.name}, Email: ${user.email}`);
}

In this example:

  • We access each user by index, which can be useful if you need to reference the position of each item in the array.
  • This approach is slightly more verbose but offers more control over the loop logic.

Using filter and forEach Together

If you only want to process certain items in the array, you can combine filter with forEach. For example, to log information only for users with a certain email domain, you can use filter to create a subset of the data before looping over it.

Example with filter and forEach

apiResponse
  .filter(user => user.email.endsWith("@example.com"))
  .forEach(user => {
    console.log(`ID: ${user.id}, Name: ${user.name}`);
  });

Here:

  • filter creates a new array with only the users whose email ends with @example.com.
  • forEach then iterates over this filtered array to log the id and name.

This chaining approach allows you to write concise, readable code that processes only the items you need.

Asynchronous API Calls with for...of and await

When fetching data from an API asynchronously, you can use for...of along with await to handle each item in sequence.

Example with Async API Response

Suppose you're making an API call to get the user data:

async function fetchUsers(): Promise<User[]> {
  const response = await fetch("https://api.example.com/users");
  return response.json();
}
async function processUsers() {
  const users = await fetchUsers();
  for (const user of users) {
    console.log(`ID: ${user.id}, Name: ${user.name}, Email: ${user.email}`);
  }
}
processUsers();

In this example:

  • fetchUsers is an asynchronous function that fetches user data and returns it as a Promise<User[]>.
  • processUsers waits for the data, then uses for...of to log each user's details.

This setup is beneficial when working with APIs, as it lets you handle asynchronous data safely.

Summary

TypeScript offers several ways to safely iterate over API response results using interfaces:

  1. Define an Interface to structure the data, making your code type-safe and error-resistant.
  2. Use for...of Loop for simple, direct access to each element.
  3. Use forEach Method for readability and functional-style iteration.
  4. Use map to create new arrays by transforming each item.
  5. Use Traditional for Loop if you need access to the index.
  6. Combine filter and forEach to selectively process items.
  7. Use Asynchronous for...of Loop with await when working with data from an API.

By leveraging TypeScript's type system and array iteration methods, you can write more robust, readable code that is better prepared for real-world API interactions. These techniques make it easy to access, manipulate, and safely work with the results from an API response.

Disclaimer: It has some affiliate links at no cost to you. Thanks for the support!

Buy here:- Practical and Comprehensive Guide to Angular

Stackademic 🎓

Thank you for reading until the end. Before you go: