Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate javascript function parameters?

Is it possible to annotate JavaScript function parameters as can be done with attributes in C#?

Example (C#):

public void DoSomething([RequiredAction(Action="some_action")] Client client) {
    // ...
}

The aim is - given a function - use reflection to inspect for instance the "type" of the parameters and perform the necessary conversions before calling it. JavaScript is indeed dynamically typed, but one could for instance want to use annotations to define the "type" of instances, a specific function expects (for instance, param should be an integer, or an array).

EDIT: The type aspect is only one possible use of an annotation. One could for instance also specify one must first run a specific function on that attribute or aspects like the maximum allowed length of an array.

One can of course use this answer and annotate the parameters by using specific parameter prefixes. For instance the Hungarian notation where sParam would identify the parameter should be a string. But that's not really convenient nor that extensible since it requires to specify names. Is there a more generic way to achieve this?

like image 607
Willem Van Onsem Avatar asked Feb 12 '23 03:02

Willem Van Onsem


2 Answers

I like to use JSDOC, these are not checked at runtime but can be checked in certain editors (komodo edit for example) and stand alone applications (I think Google closure compiler is one). An example.

/**
 * @namespace {Object} myObject
 */
var myObject = {};

/**
 * This returns true if the operand inputArg is a String.
 * @memberof myObject
 * @name something
 * @function
 * @param {*} inputArg
 * @returns {boolean}
 */
myObject.something = function (inputArg) {
    return type inputArg === 'string';
};
like image 195
Xotic750 Avatar answered Feb 13 '23 21:02

Xotic750


If you want to require the argument type, rather than comment on its type, then the closest you can do is to make a function to simulate it.


function assertType(val, type) {
    if (typeof val != 'object') {
      if (typeof val != type.name.replace(/^./, function(f){return f.toLowerCase();}))
        throw new Error("`" + val + "` is not of the data type `" + type.name + "`.");
    }
    else if (!(val instanceof type)) {
        throw new Error("`" + val + "` is not of the data type `" + type.name + "`.");
    }
}

function double(num) {
    assertType(num, Number);
    return num * 2;
}

console.log(double("malformed"));
/*
Error: `malformed` is not of the data type `number`.
    at assertType:14:9
    at double:18:2
    at eval:21:13
    at eval
*/

However, there isn't way to do this in the function declaration itself.

like image 36
Sapphire_Brick Avatar answered Feb 13 '23 22:02

Sapphire_Brick