Search⌘ K
AI Features

Discriminating Unions

Explore how discriminating unions in TypeScript help represent sum types for different states, improving code clarity and safety. Understand tag-based type narrowing and exhaustive switch checks to catch errors and simplify functional programming.

We'll cover the following...

Overview

Algebraic data types (ADTs) in functional programming can be extremely useful. We’ll discuss them in detail later on. However, in TypeScript, we can use discriminating unions (also called tagged unions) to get ...

TypeScript 3.3.4
type NetworkLoadingState = {
state: "loading";
};
type NetworkFailedState = {
state: "failed";
code: number;
};
type NetworkSuccessState = {
state: "success";
response: {
title: string;
duration: number;
summary: string;
};
};
type NetworkState = NetworkLoadingState | NetworkFailedState | NetworkSuccessState;

From the ...