Set type for function parameters?

后端 未结 12 1820
醉话见心
醉话见心 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

    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
    

提交回复
热议问题