Practical introduction to algebraic datatypes (ADTs) in TypeScript

· ITNEXT ·

1 min read Original article ↗

Product types? Sum types? Variants? Unions? …in TypeScript?!

Elias Nygren

You might already be using ADTs in your code.

Algebraic DataTypes or ADTs are specific kinds of composite types or combinations of types. The major classes of ADTs are Product types and Sum types. The big deal is that they allow you to express powerful ideas at compile time, using your type system, so you can write safe, robust code that catches bugs before runtime.

However, before we dive in to Product and Sum types, let’s start with a small coding problem and solution without ADTs. Let’s imagine we have a piece of frontend code that has to render some text based on an API response. For simplicity let’s omit things like making the API request or libraries such as React. Let’s just focus on the problem: render different things based on what the response was.

API Response => text

Simple, right? Except that our API Response has surprisingly many cases to handle (high cyclomatic complexity). Loads of nested if statements and error being thrown too… if I told you that it contains a bug, how long would it take you to figure it out (or to tell me I’m wrong)? Can the compiler tell you if…