...

/

Discriminated Unions vs Subtyping

Discriminated Unions vs Subtyping

This lesson discusses the differences between the two approaches of expressing choice in the type system.

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',
...