Discriminated Unions vs Subtyping
Explore the differences between discriminated unions and subtyping in TypeScript. Learn how each approach models complex data structures, like trees, and how they handle operations and changes in code. Understand the trade-offs between verbosity, code management, and adaptability to new types or operations.
We'll cover the following...
Overview
Subtyping is a form of type polymorphism that is very popular in Object-Oriented Programming. If you’re familiar with OOP languages such as Java or C#, then you very likely know it already.
Subtyping offers an alternative to Algebraic Data Types (discriminated unions). In this lesson, I’d like to compare these two approaches.
Defining types
Let’s go back to the example of a discriminated union representing a binary tree. It could, for example, be a tree of product categories in an e-commerce web application.
type Tree =
| { type: 'empty' }
| { type: 'leaf', value: number }
| { type: 'node', left: Tree, right: Tree };
A tree can either be:
- a node with references to left and right subtrees
- a