...

/

Discriminated Union Types

Discriminated Union Types

This lesson introduces the concept of discriminated union types.

Overview

Now that you have a full understanding of union types, let’s look at one of their special categories.

Creating discriminated unions is an extremely powerful way of composing types. Thanks to this mechanism you can write code that is type-safe beyond your imagination. Discriminated unions let you enforce some business logic rules at compile-time.

Representing choice with optional properties

Let’s start by looking at an example. Imagine implementing an e-commerce application. When the customer registers on the app, they need to provide some contact details. One of the acceptance criteria says:

Customer needs to provide either email or phone number.

The most straightforward way of defining the Customer type that satisfies this requirement is by using two ...