Advertisement
Intermediate Next.js, TypeScript with Next.js

How do you type the data returned from an API call inside a server component to get proper autocomplete and error checking?

Short answer

You define an interface describing the expected shape of the API response, and use it as the return type for your data fetching function, letting TypeScript check that your JSX correctly uses only the fields that actually exist on that data, catching mistakes before the code…

Save Next.js mock interview
Advertisement
AModel answer
You define an interface describing the expected shape of the API response, and use it as the return type for your data fetching function, letting TypeScript check that your JSX correctly uses only the fields that actually exist on that data, catching mistakes before the code ever runs.
interface Product {
  id: string;
  name: string;
  price: number;
}

async function getProduct(id: string): Promise<Product> {
  const res = await fetch(`https://api.example.com/products/${id}`);
  return res.json();
}
Real-world example
A product page defines a clear Product interface matching its API response, immediately catching an error if a developer tries to display a field, like a discount, that does not actually exist on the product data.
Likely follow-ups
  • What happens if the actual API response does not match the defined interface?
  • Should you validate the shape of API responses at runtime in addition to typing them?
Related topics