Bird
Raised Fist0
Typescriptprogramming~5 mins

Type-safe API response handling in Typescript

Choose your learning style10 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.

Practice

(1/5)
1. What is the main benefit of using type-safe API response handling in TypeScript?
easy
A. It makes the API faster to respond.
B. It removes the need for testing API responses.
C. It automatically fixes bugs in the API.
D. It helps catch errors early by defining expected data shapes.

Solution

  1. Step 1: Understand type safety purpose

    Type-safe handling means defining what data should look like before using it.
  2. Step 2: Identify the benefit

    This helps catch mistakes early, like missing or wrong data types, before running the program.
  3. Final Answer:

    It helps catch errors early by defining expected data shapes. -> Option D
  4. Quick Check:

    Type safety = Early error detection [OK]
Hint: Type safety means catching errors before running code [OK]
Common Mistakes:
  • Thinking type safety improves API speed
  • Believing it fixes bugs automatically
  • Assuming it replaces testing
2. Which TypeScript syntax correctly defines a generic function to fetch API data with a type-safe response?
easy
A. function fetchData(url: string): Promise<any> { /* ... */ }
B. function fetchData<T>(url: string): Promise<T> { /* ... */ }
C. function fetchData<T>(url: string): T { /* ... */ }
D. function fetchData(url: string): T { /* ... */ }

Solution

  1. Step 1: Understand generic function syntax

    Generic functions use <T> to represent a type parameter, allowing flexible typing.
  2. Step 2: Check return type for async fetch

    Fetching data returns a Promise of type T, so the return type must be Promise<T>.
  3. Final Answer:

    function fetchData<T>(url: string): Promise<T> { /* ... */ } -> Option B
  4. Quick Check:

    Generic + Promise = function fetchData<T>(url: string): Promise<T> { /* ... */ } [OK]
Hint: Generic fetch returns Promise of type T [OK]
Common Mistakes:
  • Returning T directly instead of Promise<T>
  • Missing generic <T> in function definition
  • Using Promise<any> loses type safety
3. Given this TypeScript code, what will be the output?
interface User { id: number; name: string; }

async function getUser(): Promise<User> {
  return { id: 1, name: "Alice" };
}

getUser().then(user => console.log(user.name));
medium
A. { id: 1, name: "Alice" }
B. 1
C. "Alice"
D. undefined

Solution

  1. Step 1: Analyze the getUser function

    It returns a Promise resolving to an object with id 1 and name "Alice".
  2. Step 2: Check the then callback

    The callback logs user.name, which is "Alice".
  3. Final Answer:

    "Alice" -> Option C
  4. Quick Check:

    user.name = "Alice" [OK]
Hint: Promise resolves to object; log property name [OK]
Common Mistakes:
  • Logging user instead of user.name
  • Confusing id with name
  • Expecting entire object printed
4. Identify the error in this TypeScript code for type-safe API response handling:
interface ApiResponse { success: boolean; data: string; }

async function fetchApi(): Promise<ApiResponse> {
  const response = await fetch('https://api.example.com');
  const json = await response.json();
  return json;
}
medium
A. Missing type assertion or validation for json before returning.
B. The fetch call should not use await.
C. The interface ApiResponse is missing a constructor.
D. The function should return void instead of Promise<ApiResponse>.

Solution

  1. Step 1: Check how json is handled

    json is returned directly without confirming it matches ApiResponse shape.
  2. Step 2: Understand type safety requirement

    TypeScript needs either a type assertion or runtime validation to ensure json fits ApiResponse.
  3. Final Answer:

    Missing type assertion or validation for json before returning. -> Option A
  4. Quick Check:

    Validate json shape before return [OK]
Hint: Always validate or assert API response type [OK]
Common Mistakes:
  • Assuming fetch json is automatically typed
  • Ignoring need for runtime checks
  • Misunderstanding async/await usage
5. You want to create a type-safe function that fetches a list of users from an API and returns only users with an active status. Which approach correctly applies type-safe API response handling?
hard
A. Define interface User with 'active' boolean, fetch data as Promise, then filter users by active before returning.
B. Fetch data as Promise<any>, filter users by active without type checking, then cast to User[].
C. Define interface User without 'active', fetch data as Promise, then filter users by active.
D. Fetch data as Promise, return data without filtering to keep type safety.

Solution

  1. Step 1: Define User interface including 'active' property

    To filter by active status, the User type must include an 'active' boolean field.
  2. Step 2: Fetch data as Promise<User[]> and filter

    Fetching with correct type ensures type safety; filtering users by active keeps the result accurate and typed.
  3. Final Answer:

    Define interface User with 'active' boolean, fetch data as Promise<User[]>, then filter users by active before returning. -> Option A
  4. Quick Check:

    Correct interface + typed fetch + filter = Define interface User with 'active' boolean, fetch data as Promise, then filter users by active before returning. [OK]
Hint: Include all needed fields in interface before filtering [OK]
Common Mistakes:
  • Casting any to User[] without checks
  • Filtering on missing properties in interface
  • Returning unfiltered data losing requirements
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard