What is the best way to tell users about my library functions that variables pass that are not of type

I am currently creating a javascript function library. Mostly for my own use, but you can never be sure that someone else will eventually use it in their projects, I at least create it as if it could happen. Most methods work only if the variables that were passed have the correct data type. Now my question is: what is the best way to warn users that a variable does not match the correct type? Should someone miss such an error?

function foo(thisShouldBeAString){ //just pretend that this is a method and not a global function
 if(typeof(thisShouldBeAString) === 'string') {
  throw('foo(var), var should be of type string');
 }
 #yadayada
}

I know that javascript does an internal type conversion, but it can create very strange results (for example, "234" + 5 = "2345", but "234" * 1 = 234), and this can make my methods very strange.

EDIT
To make things clearer: I don't want to do type conversion, the passed variables must be of the correct type. What is the best way to tell the user of my library that the variables passed are not of the type?

+5
source share
6 answers

Some small notes on type checking - this is actually not so difficult:

Use typeofto test primitives and instanceofto test certain types of objects.

:

typeof x === 'string'

typeof x === 'string' || x instanceof String

.

,

x instanceof Array

( - , Firefox 3.0.5 , window instanceof Object === false window.__proto__ instanceof Object === true).

edit: :

typeof func === 'function' func instanceof Function.

, ( 'object'). - ...

edit2: , /, , .. instanceof . : , Object.prototype.toString.call(x) === '[object Array]'.

+2

, . : -

var s = new String("Hello World!");
alert(typeof s);

? Ans: "". - , . , , .

, Javascript, ( true, ), : -

String.prototype.isString = true;
Number.prototype.isNumber = true;
Boolean.prototype.isBoolean = true;
Date.prototype.isDate = true;
Array.prototype.isArray = true;

, , : -

if (x.isString)

null/ undefined: -

if (x != null && x.isString)

new String("thing") gotcha, , , .

+4

, jQuery, .

, , , .

, JavaScript, -.

PS. , , JavaScript.

+1

?

You can always define the data type 'string'. Is not it?

0
source

You can check some value, for example "debug = 1". If there is, you can display errors, such as alerts. Therefore, in development mode, the user will see them, but on a real site, he will disable it. An error message does not appear in the same browser browser - you need to look at the JS console.

There is also a FireBug. You can detect this and put also FB debugging messages.

0
source

All Articles