Annotate javascript function parameters?
Asked Answered
I

2

7

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?

Immerge answered 18/1, 2015 at 12:40 Comment(5)
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.)Thursday
@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.Immerge
Basically no, the best you can do is use comments other than the suggestions that you have already made, i.e. the notation.Jelks
Have you looked into Typescript? It adds optional type annotations and compile-time type checking.Phenomena
@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...Immerge
J
10

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';
};
Jelks answered 18/1, 2015 at 13:0 Comment(0)
H
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.

Headrace answered 7/11, 2019 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.