0.0.5 • Published 11 years ago

method-signature v0.0.5

Weekly downloads
35
License
-
Repository
github
Last release
11 years ago

method-signature

A clean-ish way to add runtime type assertions to methods in Javascript.

The types of a methods arguments and return values can be declared. They will be checked when the method is called, and an error will be thrown if the wrong type is passed in or returned.

Example Usage

Simple example - we declare a method named methodName that takes two number arguments and returns a string.

We use the sig() to declare the types. The first argument is the name of the method. The next is an array of strings representing the types of the method's arguments. The final argument to sig() is the type of the return value.

sig('methodName', ['number', 'number'], 'string');
obj.methodName = function() {
  // actual method definition here
}

// After one or many calls to sig() as above, call enforce() to decorate all
// the methods with the type checking logic:
sig.enforce(obj);

The type strings (like 'number' and 'string' above) can be primitive javascript types (object, number, string, boolean) or class names (the result of calling value.constructor.name).

A more complete example should make it clearer (maybe..). This is how I tend to define classes in Javascript. I'm using amd here - but that's not required.

define(['method-signature'], function(sig) {

  var s = SillyAdder, p = s.prototype;

  function SillyAdder(num) {
    this.num = num;
  }

  sig('add', ['number'], 'number');
  p.add = function(anotherNum) {
    return this.num + anotherNum;
  };

  sig('subtract', ['number'], 'number');
  p.subtract = function(anotherNum) {
    return this.num - anotherNum;
  };

  sig.enforce(p);

  return s;
});
0.0.5

11 years ago

0.0.4

11 years ago

0.0.2

11 years ago

0.0.1

11 years ago