2

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 }
  });
  // ...
};
12
  • 2
    You could use a loop and have an object tell the types: validateObj = { "foo":"number","bar":"text" } Commented Aug 26, 2013 at 7:58
  • Is there a pre-made function that does that? Of course it's possible to create it for yourself, but if there's already a widely used solution, I'd prefer sticking to it. Commented Aug 26, 2013 at 8:00
  • Use the typeof operator Commented Aug 26, 2013 at 8:03
  • Please see the updated part of my question, a simple typeof is 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). Commented Aug 26, 2013 at 8:03
  • 2
    @GoloRoden With vanilla JavaScript, you're on your own for this. You could give TypeScript a try, which handles many of the type checks. Commented Aug 26, 2013 at 8:04

7 Answers 7

1

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 is missing.'); }
  if (typeof options.foo !='number') { throw new Error('foo is missing.'); }
  if (typeof options.bar !='string') { throw new Error('bar is missing.'); }
  if (typeof callback!= 'function') { throw new Error('callback is missing.'); }
  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could do like this:

var x = function (options, callback) {
    var options = options || {};
    if (typeof options.foo != 'number') {
        throw new Error('foo need to be a number.');
    }
    if (typeof options.bar != 'string') {
        throw new Error('bar need to be a string.');
    }
    // ...
}

Comments

0

Use typeof

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!

...

2 Comments

typeof new Number(3.14) === 'object'.
"Despite being "Not-A-Number"" Just to make sure: This is not an error in JS (like typeof null), this is in compliance with the IEEE 754 standard. NaN is a special number value.
0

See these examples for checking the type, string or integer:

if(typeof(somevar) === 'string') alert('string');
if(typeof(somevar)==="number" && Math.round(somevar) == somevar) alert('is int');

2 Comments

typeof somevar is the preferred syntax. It is an operator and not a function
Also, the Match.round(), why? Maybe 12.4 should be correct too (though typeof might need a change to float). This is an action which doesn't add allot and does slow down
0
if (myObj.hasOwnProperty(myProp)) { //to check whether mentioned property exist
    if (typeof myObj[myProp] == "string") { //or integer
        // your code to be executed!!!
    } else {
        //ERROR!!!
    }
}

Comments

0

While this is not exactly the idea behind javascript's type model, I usually used a for-loop to iterate over the data members of my to-check-object:

/* (.startsWith has to be implementes somehow) */
for (key in my_object_with_data) {
    if (!key.startsWith(typeof my_object_with_data[key]+"_") {
        /* The member "key" has wrong type. */
    }
}

The members of the object have to be named number_a for example to check it's type for being a number.

Additional validation can be done via some generic check methods, that can be applied inside the for loop according to the typeof value.

Comments

0

Okay, I found a library that does what I want by myself, it's called ArgueJS:

function range(){ 
  arguments = __({start: [Number, 0], stop: Number, step: [Number, 1]})

  for(var i = arguments.start; i < arguments.stop; i += arguments.step)
    console.log(i);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.