An Introduction to ADTs and Structural Pattern Matching in TypeScript
- According to the docs, the programmer needs three things in order to create an algebraic data type in TypeScript: – – Following these guidelines, let’s approximate our Haskell type : – – In the above example, the and interfaces both have a common, singleton type property – (item ).
- We can use the type guard to build a type safe function, too: – – With the compiler option enabled, TypeScript will fail to compile our function if it omits one or more of the type’s singleton properties ( , in this example), because the function would implicitly return for…
- An interesting property of a TypeScript disjoint union type is that it cannot be extended with additional types after its initial declaration.
- 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.
- 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).
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.
@palashv2: 🔥 An Introduction to Algebraic Data Types and Structural Pattern Matching in TypeScript: …
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.
In Haskell, we define an algebraic data type – 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 is either a (“we succeed with a value of type “) or a (“we failed” with a value of type ). Functions that return a can indicate one or the other but not both.
When interacting with a value of type , 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:
Following these guidelines, let’s approximate our Haskell type :