Set type for function parameters?

后端 未结 12 1786
醉话见心
醉话见心 2020-11-30 18:37

Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:



        
相关标签:
12条回答
  • 2020-11-30 19:09

    Use typeof or instanceof:

    const assert = require('assert');
    
    function myFunction(Date myDate, String myString)
    {
        assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
        assert( myDate instanceof Date,         'Error message about incorrect arg type');
    }
    
    0 讨论(0)
  • 2020-11-30 19:09

    I've been thinking about this too. From a C background, you can simulate function return code types, as well as, parameter types, using something like the following:

    function top_function() {
        var rc;
        console.log("1st call");
        rc = Number(test_function("number", 1, "string", "my string"));
        console.log("typeof rc: " + typeof rc + "   rc: " + rc);
        console.log("2nd call");
        rc = Number(test_function("number", "a", "string", "my string"));
        console.log("typeof rc: " + typeof rc + "   rc: " + rc);
    }
    function test_function(parm_type_1, parm_val_1, parm_type_2, parm_val_2) {
        if (typeof parm_val_1 !== parm_type_1) console.log("Parm 1 not correct type");
        if (typeof parm_val_2 !== parm_type_2) console.log("Parm 2 not correct type");
        return parm_val_1;
    }
    

    The Number before the calling function returns a Number type regardless of the type of the actual value returned, as seen in the 2nd call where typeof rc = number but the value is NaN

    the console.log for the above is:

    1st call
    typeof rc: number   rc: 1
    2nd call
    Parm 1 not correct type
    typeof rc: number   rc: NaN
    
    0 讨论(0)
  • 2020-11-30 19:11

    Not in javascript it self but using Google Closure Compiler's advanced mode you can do that:

    /**
     * @param {Date} myDate The date
     * @param {string} myString The string
     */
    function myFunction(myDate, myString)
    {
        //do stuff
    }
    

    See http://code.google.com/closure/compiler/docs/js-for-compiler.html

    0 讨论(0)
  • 2020-11-30 19:15

    Check out the new Flow library from Facebook, "a static type checker, designed to find type errors in JavaScript programs"

    Definition:

    /* @flow */
    function foo(x: string, y: number): string {
      return x.length * y;
    }
    foo('Hello', 42);
    

    Type checking:

    $> flow
    hello.js:3:10,21: number
    This type is incompatible with
      hello.js:2:37,42: string
    

    And here is how to run it.

    0 讨论(0)
  • 2020-11-30 19:15

    It can easilly be done with ArgueJS:

    function myFunction ()
    {
      arguments = __({myDate: Date, myString: String});
      // do stuff
    };
    
    0 讨论(0)
  • 2020-11-30 19:16

    Maybe a helper function like this. But if you see yourself using such syntax regularly, you should probably switch to Typescript.

    function check(caller_args, ...types) {
        if(!types.every((type, index) => {
            if(typeof type === 'string')
                return typeof caller_args[index] === type
            return caller_args[index] instanceof type;
        })) throw Error("Illegal argument given");
    }
    
    function abc(name, id, bla) {
       check(arguments, "string", "number", MyClass)
       // code
    }
    
    0 讨论(0)
提交回复
热议问题