最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reflection - Annotate javascript function parameters? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited May 23, 2017 at 11:43 CommunityBot 11 silver badge asked Jan 18, 2015 at 12:40 willeM_ Van OnsemwilleM_ Van Onsem 477k33 gold badges473 silver badges612 bronze badges 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.) – nnnnnn Commented Jan 18, 2015 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 Commented Jan 18, 2015 at 12:43
  • 2 Basically no, the best you can do is use ments other than the suggestions that you have already made, i.e. the notation. – Xotic750 Commented Jan 18, 2015 at 12:51
  • 2 Have you looked into Typescript? It adds optional type annotations and pile-time type checking. – Pieter Witvoet Commented Jan 18, 2015 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 Commented Jan 18, 2015 at 12:59
Add a ment  | 

2 Answers 2

Reset to default 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 piler 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';
};

If you want to require the argument type, rather than ment 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.

发布评论

评论列表(0)

  1. 暂无评论