Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Reusable Patterns | Advanced Type Patterns and Best Practices
Working with Interfaces and Generics in TypeScript

bookReusable Patterns

When working with APIs in real-world applications, you often need to handle responses that follow a consistent structure but may contain different types of data. For example, an API might return user data in one response and product data in another, but both responses share common properties like a status code and potential error messages. To avoid rewriting similar types for every endpoint, you can use a reusable, generic API response type that adapts to any kind of data payload.

123456
// Define a generic interface for API responses interface ApiResponse<T> { data: T | null; error: string | null; status: number; }
copy

This ApiResponse<T> interface allows you to specify the type of the data property using a generic parameter. You can use ApiResponse<User> for a user-related endpoint, or ApiResponse<Product> for a product-related endpoint, ensuring type safety and consistency across your codebase. For example, suppose you have the following user and product types:

type User = {
  id: number;
  name: string;
};

type Product = {
  id: number;
  title: string;
  price: number;
};

You can then type your API responses as ApiResponse<User> or ApiResponse<Product>, depending on what data you expect from the server. This pattern helps you avoid duplicating code and makes it easier to manage changes across your application.

123456789101112131415161718
// Example function that fetches user data and returns a typed ApiResponse<User> async function fetchUser(userId: number): Promise<ApiResponse<User>> { try { // Simulate fetching user data from an API const user: User = { id: userId, name: "Alice" }; return { data: user, error: null, status: 200, }; } catch (e) { return { data: null, error: "Failed to fetch user", status: 500, }; } }
copy
question mark

What is the main advantage of defining the ApiResponse<T> interface with a generic type parameter in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Suggested prompts:

Can you show an example of how to use ApiResponse with a Product type?

How would I handle errors using this ApiResponse interface?

Can you explain how generics work in this context?

Awesome!

Completion rate improved to 9.09

bookReusable Patterns

Scorri per mostrare il menu

When working with APIs in real-world applications, you often need to handle responses that follow a consistent structure but may contain different types of data. For example, an API might return user data in one response and product data in another, but both responses share common properties like a status code and potential error messages. To avoid rewriting similar types for every endpoint, you can use a reusable, generic API response type that adapts to any kind of data payload.

123456
// Define a generic interface for API responses interface ApiResponse<T> { data: T | null; error: string | null; status: number; }
copy

This ApiResponse<T> interface allows you to specify the type of the data property using a generic parameter. You can use ApiResponse<User> for a user-related endpoint, or ApiResponse<Product> for a product-related endpoint, ensuring type safety and consistency across your codebase. For example, suppose you have the following user and product types:

type User = {
  id: number;
  name: string;
};

type Product = {
  id: number;
  title: string;
  price: number;
};

You can then type your API responses as ApiResponse<User> or ApiResponse<Product>, depending on what data you expect from the server. This pattern helps you avoid duplicating code and makes it easier to manage changes across your application.

123456789101112131415161718
// Example function that fetches user data and returns a typed ApiResponse<User> async function fetchUser(userId: number): Promise<ApiResponse<User>> { try { // Simulate fetching user data from an API const user: User = { id: userId, name: "Alice" }; return { data: user, error: null, status: 200, }; } catch (e) { return { data: null, error: "Failed to fetch user", status: 500, }; } }
copy
question mark

What is the main advantage of defining the ApiResponse<T> interface with a generic type parameter in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 1
some-alt