Annotate javascript function parameters?

Willem Van Onsem picture Willem Van Onsem · Jan 18, 2015 · Viewed 10.2k times · Source

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?

Answer

Xotic750 picture Xotic750 · Jan 18, 2015

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';
};