- Typescript Daily
- Posts
- Overlooking Union Types? That's a Big Mistake!
Overlooking Union Types? That's a Big Mistake!
Discover why discriminated unions in TypeScript are transforming the coding paradigm.
🎯 TypeScript Daily Digest!
Advanced Feature: Union Types & Discriminated Unions in TypeScript
Problem Statement: You have different types of payment methods in an e-commerce platform: "creditCard", "PayPal", and "bank transfer". How can you manage and type-check this variability without causing a mess in your code?
🎁 Basic Example: Multiple Payment Methods
Scenario: An e-commerce platform wants to accept payments via multiple methods - credit card, PayPal, and bank transfer.
Explanation: This example uses Union Types to specify that a PaymentMethod
can be any one of CreditCard
, PayPal
, or BankTransfer
. The kind
field is used as a discriminant to safely switch between these types.
🎨 Medium Example: UI Components with Variations
Scenario: You're building a UI component library, and your button component has different variations - primary, secondary, and icon.
Explanation: This example progresses to showing how union types can be used in a real-world library of UI components, with a discriminant (kind
field) to determine how each variant of a component should be rendered.
🔌 Advanced Example: Parsing API Responses
Scenario: You're developing a function that handles responses from an API. The responses could be a success, error, or redirect, and each has a different data structure.
Explanation: In this advanced example, we demonstrate how Discriminated Unions can be used to elegantly handle varying response structures from an API, again using a common field (status
in this case) as a discriminant to safely and clearly handle different cases.
While these are just some of the examples to illustrate the power of Union Types, there are multiple other scenarios where this could be helpful even in your projects. If you are more interested to know more about some of the real-world use cases, please keep reading further. Below we discuss 10 real-world use cases where you can apply Union Types.
Real-World use-cases:
🛒 1. Handling Multiple Payment Methods in E-Commerce Applications
Allows for defining distinct types for Credit Card, PayPal, Bank Transfer, etc., and writing functions to process payments that are type-safe and easy to extend.
🎨 2. Building Flexible UI Component Libraries
Discriminated Unions can be used to define different variations of a component, where each variation has its unique set of properties, allowing a clean and safe rendering based on the component type.
🔌 3. Parsing and Handling Diverse API Responses
For APIs that can return different shapes of data (success, error, redirect, etc.), Discriminated Unions ensure that the appropriate handling code is triggered based on the response type.
📄 4. Modeling Complex Forms with Conditional Fields
Reply