To quote Rúnar Bjarnason:
One of the great features of modern programming languages is structural pattern matching on algebraic data types. Once you’ve used this feature, you don’t ever want to program without it. You will find this in languages like Haskell and Scala.
I couldn’t agree more myself. That said, I spend most of my time writing programs with languages that don’t have first-class support for algebraic data types (ADTs). So what’s a programmer to do?
This blog post provides examples of two ways to approximate structural pattern matching in TypeScript. The class-based example borrows heavily from Bjarnason’s excellent blog post Structural Pattern Matching in Java, and the discriminated union example was inspired by the Advanced Types section of the TypeScript documentation and countless conversations with Michael Avila, one of my coworkers.
What’s an ADT Look Like? (Obligatory Haskell Example)
In Haskell, we define an algebraic data type
Failable – a type which represents the disjoint union of success and failure-values – with the following syntax:
What we’re saying here is that a value of type
Failable t e is either a
Success t (“we succeed with a value of type
t“) or a
Failure e (“we failed” with a value of type
e). Functions that return a
Failable can indicate one or the other but not both.
When interacting with a value of type
Failable, we need to pattern match on the type’s constructor if we want to perform operations on their underlying values.
According to the docs, the programmer needs three things in order to create an algebraic data type in TypeScript:
- Types that have a common, singleton type property — the _discriminant_.
- A type alias that takes the union of those types — the _union_.
- Type guards on the common property.
Following these guidelines, let’s approximate our Haskell type
In the above example, the
Success interfaces both have a common, singleton type property –
#1). These interfaces are unioned together to form our ADT,
#2). For any function accepting a
Failable to be well typed it must first examine the value of the
tag before making use of
Success-specific properties (item
We can use the
tag type guard to build a type safe
failable function, too:
Interesting Property A: Exhaustiveness Checking
With the compiler option
strictNullChecks enabled, TypeScript will fail to compile our
failable function if it omits one or more of the type’s singleton properties (
tag, in this example), because the function would implicitly return
undefined for the unhandled type and
undefined is not an inhabitant of our return type,
Interesting Property B: Inextensibility
An interesting property of a TypeScript disjoint union type is that it cannot be extended with additional types after its initial declaration. This is a good thing, as allowing library consumers to extend a disjoint union with their own types would cause compilation errors in existing code (due to failed exhaustiveness checks).
Interesting Property C: Naming the Switching Function
A thing that I find irritating about this approach is the fact that I will need to come up with an original name for the matching function associated with each disjoint union type. While
failable seems sensible, I’ve run into things like
The Classical Approach
If discriminated unions aren’t your thing, ADTs can be approximated using an abstract class:
Interesting Property A: Familiarity
This is the pattern that I use in Java. If you do too, perhaps it makes sense to stick with it in your TypeScript instead of introducing a new pattern.
Interesting Property B: Extensibility
Unlike the disjoint union type, our abstract class can be extended by any programmer who imports it (to my knowledge, as TypeScript contains no mechanism by which a programmer can “seal” a class). That said, such a thing would have little effect, as the
Failable#match method would not contain a parameter for this new type.
A Real-World Example
instanceof stuff required) provided that they guard on the common property.
In the following example, we define a function
parseLogLine which accepts a line of text from a log file as a
String and returns a
InfoMessage (if the string was parseable as a log-line) or
Unknown (if it was not).
I find algebraic data types to be a fun and useful tool in my tool belt, even if the language of my day job doesn’t provide first-class support for them. Love them? Think they’re stupid? Leave your feedback in the comments section, below.