5

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?

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • JavaScript function parameters (and variables in general) don't have a type. (JavaScript *values* have a type, but a given variable can refer to different types.) – nnnnnn Jan 18 '15 at 12:42
  • @nnnnnn: I know that, but that doesn't imply the *algorithm* doesn't expect a certain type. Even in extremely dynamically typed languages like `bash` shell, one must make contracts about what to pass and what not. An example of a "type" could be that the method only accepts positive numbers. Thus they don't have to map on any predefined type system. – Willem Van Onsem Jan 18 '15 at 12:43
  • 2
    Basically no, the best you can do is use comments other than the suggestions that you have already made, i.e. the notation. – Xotic750 Jan 18 '15 at 12:51
  • 2
    Have you looked into `Typescript`? It adds optional type annotations and compile-time type checking. – Pieter Witvoet Jan 18 '15 at 12:56
  • @PieterWitvoet: that's an improvement. But the types should also be checked at runtime (and not only types) such that if a function is passed to another function. The second can inspect the first and make a decision based on that... – Willem Van Onsem Jan 18 '15 at 12:59

2 Answers2

8

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';
};
victorlin
  • 638
  • 7
  • 14
Xotic750
  • 22,914
  • 8
  • 57
  • 79
1

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.

Sapphire_Brick
  • 1,560
  • 12
  • 26