Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Discriminated Unions in Real-World Modeling | Discriminated Unions and Exhaustive Handling
Quizzes & Challenges
Quizzes
Challenges
/
Error Handling and Type Guards in TypeScript

bookDiscriminated Unions in Real-World Modeling

12345678910111213141516171819202122232425
// Define a discriminated union for API responses type ApiResponse = | { status: "success"; data: string } | { status: "error"; message: string } | { status: "loading" }; // Function that handles different API response types function handleApiResponse(response: ApiResponse) { switch (response.status) { case "success": console.log("Data received:", response.data); break; case "error": console.error("Error:", response.message); break; case "loading": console.log("Loading..."); break; } } // Example usages handleApiResponse({ status: "success", data: "User profile loaded." }); handleApiResponse({ status: "error", message: "Network error." }); handleApiResponse({ status: "loading" });
copy

Discriminated unions are a powerful way to model real-world scenarios in TypeScript, especially when dealing with data that can exist in multiple, clearly defined states. In applications that interact with APIs, you often encounter responses that can represent a successful data fetch, an error, or a loading state. By using a discriminated union, you can represent all possible response shapes in a single type, making your code easier to read and maintain.

Each variant of the union includes a unique status property, which acts as the discriminant. This property allows TypeScript to narrow the type automatically inside a switch statement or conditional check. When you handle an API response, you can switch on the status and TypeScript will enforce that you only access properties that are valid for that specific variant. This reduces the risk of runtime errors and makes your code more robust.

Exhaustive handling is crucial in this context. By covering every possible value of the discriminant property in your logic, you ensure that your code will not silently ignore new states if the union is expanded in the future. TypeScript can help catch missing cases, especially when combined with strict settings or never checks. This is particularly important in real-world applications where API responses may evolve, and failing to handle a new response type could lead to bugs or incomplete features.

question mark

Which of the following is a primary benefit of using discriminated unions for modeling API responses in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2

Chieda ad AI

expand

Chieda ad AI

ChatGPT

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

Awesome!

Completion rate improved to 5.88

bookDiscriminated Unions in Real-World Modeling

Scorri per mostrare il menu

12345678910111213141516171819202122232425
// Define a discriminated union for API responses type ApiResponse = | { status: "success"; data: string } | { status: "error"; message: string } | { status: "loading" }; // Function that handles different API response types function handleApiResponse(response: ApiResponse) { switch (response.status) { case "success": console.log("Data received:", response.data); break; case "error": console.error("Error:", response.message); break; case "loading": console.log("Loading..."); break; } } // Example usages handleApiResponse({ status: "success", data: "User profile loaded." }); handleApiResponse({ status: "error", message: "Network error." }); handleApiResponse({ status: "loading" });
copy

Discriminated unions are a powerful way to model real-world scenarios in TypeScript, especially when dealing with data that can exist in multiple, clearly defined states. In applications that interact with APIs, you often encounter responses that can represent a successful data fetch, an error, or a loading state. By using a discriminated union, you can represent all possible response shapes in a single type, making your code easier to read and maintain.

Each variant of the union includes a unique status property, which acts as the discriminant. This property allows TypeScript to narrow the type automatically inside a switch statement or conditional check. When you handle an API response, you can switch on the status and TypeScript will enforce that you only access properties that are valid for that specific variant. This reduces the risk of runtime errors and makes your code more robust.

Exhaustive handling is crucial in this context. By covering every possible value of the discriminant property in your logic, you ensure that your code will not silently ignore new states if the union is expanded in the future. TypeScript can help catch missing cases, especially when combined with strict settings or never checks. This is particularly important in real-world applications where API responses may evolve, and failing to handle a new response type could lead to bugs or incomplete features.

question mark

Which of the following is a primary benefit of using discriminated unions for modeling API responses in TypeScript?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2
some-alt