Type check JavaScript with sanctuary-def

Rafi
computer Stuff
Published in
2 min readMar 13, 2017

JavaScript is awesome and flexible but sometime this dynamic typing comes
at cost. It can sometime result in awful errors that will be hard to detect.
while we don’t want to loose these advantages of dynamic typing it would be awesome if we could leverage some of the advantages of static typing without loosing another language that compiles to JavaScript.

sanctuary-def provides enables us to create optional type system that we can use as tool during development to aid us and can disable it in production. So it’s not some new language that compiles to Js but just plain Js and the type system will not stand in our way.

to enable this type checking you do

const $ = require('sanctuary-def');
const def = $.create({
checkTypes: process.env.NODE_ENV === 'development',
env: $.env,
});

why the $ you may ask it is just a convention that is followed by sanctuary-def nothing special if you want you could name it whatever you want.

The create method of $ allows you to setup the environment. The checkTypes if set true enables type checking. We have used

process.env.NODE_ENV === 'development',

to enable type checking during development and disable it in production to improve performance. Here we have used the default environment ($.env) that comes with sanctuary-def. It comes by default some types like

Function, Arguments, Array, Boolean, Date, Error, Null, Number, Object, RegExp, sanctuary-def/StrMap, String, Undefined …etc

so if I were to create a function called add that would take two Numbers and
return a result which is a Number we could do

const add = def('add', {}, [$.Number, $.Number, $.Number],
(x, y) => x + y);

the first two argument in the array [$.Number, $.Number, $.Number] indicate the input to the function and the last argument indicates the output.

The function add is now curried by default meaning that add will take
an argument and return function that will take argument and return sum. Here is awesome video explaining that.

But if you want to define custom types which is not provided by sanctuary-def
you could do that by just adding new elements to the array $.env and pass
the new array instead to the create method.

const env = $.env.concat([Integer, NonZeroInteger]);

And if you want to remove some existing types you could also do the same by
just removing the elements from the $.env and pass the new array to the create method.

--

--

Rafi
computer Stuff

I'm developer who works mostly with JS and python. In my free time I like to play with data and contribute to open source