Typista is a JavaScript library that provides a compact syntax for defining an abstract class along with a set of associated concrete classes. Using Typista, one may write
const Maybe = data('Maybe');
Maybe.$ = $.Nothing
| $.Just('x');
rather than
class Maybe {}
class Nothing extends Maybe {}
class Just extends Maybe {
constructor(x) {
super();
this.x = x;
}
}
That is, Typista simplifies the definition of structured types 1 – also known as algebraic data types 2, variant types 3 or custom types 4.
Typista can be installed via npm with the following command:
npm install typista
In the following, we show how to define a Maybe
data type useful to represent optional values. We define this new type by means of the data
function.
const {data, $} = require('typista');
const Maybe = data('Maybe');
A value of type Maybe
may either be empty or contain a value x
. We represent this fact by means of two constructors, named Nothing
and Just
. They are introduced via a combination of $
and |
, as to denote alternatives.
const {data, $} = require('typista');
const Maybe = data('Maybe');
Maybe.$ = $.Nothing
| $.Just('x');
Despite the different syntax, Maybe.Just
and Maybe.Nothing
are just plain JavaScript constructor functions. As such, it is possible to define methods by attaching functions to the corresponding prototype object. For instance, we may define a method that map
s optional values according to a transformation function.
Maybe.Just.prototype.map = function (fn) {
return new Maybe.Just(fn(this.x));
};
Maybe.Nothing.prototype.map = function (fn) {
return this;
};
Expectedly, we instantiate values by invoking the related constructor. The only notable difference is the possibility of omitting the new
keyword, if so desired.
const m1 = new Maybe.Just(5); // => Just { x: 5 }
const m2 = m1.map(x => x + 2); // => Just { x: 7 }
const m3 = new Maybe.Nothing(); // => Nothing {}
const m4 = m3.map(x => x + 2); // => Nothing {}
[1]: Simon Peyton Jones – The Implementation of Functional Programming Languages
[2]: Wikipedia – Algebraic Data Type
[3]: ReasonML – Variants
[4]: Elm – Custom Types
Icons made by Freepik from www.flaticon.com