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:
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');
}
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
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
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.
It can easilly be done with ArgueJS:
function myFunction ()
{
arguments = __({myDate: Date, myString: String});
// do stuff
};
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
}