Harry Yates

I'm a web developer focused on TypeScript, React, and Three.js.

Typescript Discriminated Unions

Tue, 30th Apr 2024

TypeScript offers a structured approach to managing diverse data with its discriminated unions.

This feature is a powerful tool for handling multiple response structures from APIs, ensuring code clarity and reliability.

Post

Understanding the Challenge with API Responses

Handling API responses effectively poses a significant challenge in web development. Traditional methods often lead to complex checks for optional properties, which can obscure the clarity of the code and introduce potential errors.

The Solution: Discriminated Unions

Discriminated unions in TypeScript simplify the handling of different data structures by ensuring type safety and clarity. They use a common property—known as the discriminator—to distinguish between types within a union, clarifying which properties are available in each scenario.

Exploring a Typical Scenario: Success and Error Responses

Consider an API that can either return a successful data object or an error message. Discriminated unions allow us to define these possible outcomes explicitly:

Post

With these definitions, the type of response is linked directly to the success property, guiding developers on how to handle each type of response correctly.

Practical Example: Implementing get<T>()

Here’s how you can implement a function to fetch data using the discriminated union:

Post

This approach eliminates excessive type checks and ensures that each part of your code handles data appropriately based on the defined types.

The Benefits of Discriminated Unions
  • Clarity: They provide a clear structure for different data types, making it easier to understand and maintain the code.
  • Type Safety: TypeScript enforces correct usage of the data structures, reducing runtime errors.
  • Efficiency: Reduces the need for repetitive and error-prone type checks throughout your application.