Check function parameters for existence and type in JavaScript -
supposed have function defined such as:
var x = function (options, callback) { /* ... */ }
options
needs have properties foo
, bar
, foo
shall of type number
, , bar
of type string
.
so, basically, check using following code:
var x = function (options, callback) { if (!options) { throw new error('options missing.'); } if (!options.foo) { throw new error('foo missing.'); } if (!options.bar) { throw new error('bar missing.'); } if (!callback) { throw new error('callback missing.'); } // ... }
but checks existence, not yet correct types. of course can add further checks, becomes lengthy, , not readable. once start talking optional parameters, gets mess, parameter-shifting , on …
what best way deal (supposed want check it)?
update
to clarify question: know there typeof
operator, , know how deal optional parameters. have these checks manually, , - sure - not best can come with.
the goal of question was: there ready-made function / library / whatever can tell expecting 5 parameters of specific types, mandatory, optional, , function / library / whatever checks , mapping you, comes down one-liner?
basically, such as:
var x = function (options, callback) { verifyargs({ options: { foo: { type: 'number', mandatory: true }, bar: { type: 'string', mandatory: true } }, callback: { type: 'function', mandatory: false } }); // ... };
javascript has typeof
console.log( typeof '123' ); // string console.log( typeof 123 ); // number console.log( typeof undefinedvar); // undefined var x = function (options, callback) { if (typeof options =='undefined' { throw new error('options missing.'); } if (typeof options.foo !='number') { throw new error('foo missing.'); } if (typeof options.bar !='string') { throw new error('bar missing.'); } if (typeof callback!= 'function') { throw new error('callback missing.'); } // ... }
Comments
Post a Comment