1

Is there a node.js library that verifies arguments list to check if they conform to the arguments I want.

Like here's a function I want to write:

function my(a [,b], done);

a is required, and should be an object. b is optional but should be an array. done is the callback and should be a function.

Is there a library that would do all the necessary checks and substitutions (if(!done)done=b) etc automatically?

2
  • 1
    Is switching to TypeScript not an option here? Commented Nov 29, 2014 at 9:16
  • @DeerHunter That only works as long as the script is used in a TypeScript-only environment, i.e. when TypeScript's type checking system has the ability to run at compile time.
    – ComFreek
    Commented Nov 29, 2014 at 18:22

1 Answer 1

2

There's three that I found;

typed-function

var typed = require('typed-function');

// create a typed function
var fn1 = typed('number, *': function (a, b) {
  return 'a is a number, b can be anything';
});

https://github.com/josdejong/typed-function

check-args

var accept = require("check-args-lib")

var fn = accept(Number).accept(String).to(function(dyna) {
  // do something with dyna...
  // If the type checking is enabled, you can now be sure it is
  // defined and it is a number or a string
});

https://github.com/artarf/check-args

argue

var argue = require('argue');

function foo() {
  var sig = argue(arguments);
  switch(sig) {
    case 'sbnf':
      var mystr = arguments[0];
      var mybool = arguments[1];
      var mynum = arguments[2];
      var myfunv = arguments[3];
      // we got a string, boolean, number, and function
      break;

    case 'nnnn':
      // we got four numbers
      break;

    case 'ord-':
      // we got an object, regexp, date, and null
      break;

    default:
      // you get the idea
  }
}

https://github.com/ifit/Argue

I'd say I like check-args most out of the three as it provides a way to remove this sort of code in production very easily. typed-function has a pretty nice syntax, and argue is alright too, but is more like a helper for doing things like typeof checks than actually throwing any error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.