Algebraic Data Types

Topics: Language Specification
Aug 15, 2013 at 10:10 PM
As someone who mostly thinks in functional languages, I really miss ADTs in TypeScript. Is there any intention that they will make it into the language? Or are there idiomatic ways, which I have overlooked, to achieve similar things using the current TypeScript type system?
Nov 7, 2013 at 3:03 AM
I'd also love to see algebraic data types in Typescript (and maybe Scala-style views, although I havn't thought about it as much). They are a really powerful way to ensure a lot more compile-time correctness.
Developer
Nov 7, 2013 at 7:19 PM
Feel free to upvote this issue https://typescript.codeplex.com/workitem/1364
Sep 7, 2014 at 6:59 AM
What I did is inspired by the way F# compiles an ADT into the CLR, which doesn't seem to have direct support for it. Its a bit hard to explain textually but I try: For every constructor of the ADT you create a (potentially private) class that derives from a common interface. The interface has at a method (i call it case) that allows to dispatch (through virtual method dispatch) between the alternatives. The method has one parameter for each alternative: a function with a signature corresponding to the signature of the constructor.
An example for a binary tree is here:
This case method then can be the basis for any other method on the ADT. It is also convenient and straightforward to implement a fold (catamorphism) for the ADT.