Supposed I have a function defined such as:
var x = function (options, callback) { /* ... */ }
options needs to have properties foo and bar, where foo shall be of type number, and bar of type string.
So, basically, I could check this using the following code:
var x = function (options, callback) {
if (!options) { throw new Error('options is missing.'); }
if (!options.foo) { throw new Error('foo is missing.'); }
if (!options.bar) { throw new Error('bar is missing.'); }
if (!callback) { throw new Error('callback is missing.'); }
// ...
}
But this only checks for existence, not yet for correct types. Of course I can add further checks, but this soon becomes lengthy, and not so well readable. Once we start talking about optional parameters, it gets a mess, with parameter-shifting and so on …
What is the best way to deal with this (supposed that you want to check it)?
UPDATE
To clarify my question: I know that there is the typeof operator, and I also know how to deal with optional parameters. But I have to do all these checks manually, and this - for sure - is not the best we can come up with.
The goal of my question was: Is there a ready-made function / library / whatever that you can tell that you are expecting five parameters of specific types, some mandatory, some optional, and the function / library / whatever does the checks and the mapping for you, so that all this comes down to a one-liner?
Basically, something such as:
var x = function (options, callback) {
verifyArgs({
options: {
foo: { type: 'number', mandatory: true },
bar: { type: 'string', mandatory: true }
},
callback: { type: 'function', mandatory: false }
});
// ...
};
typeofis not what I want (and I am fully aware of this solution, but it soon becomes a mess, when you have lots of parameters you want to check).