Proposal: is.primitive() to test for boolean, number, or string
Opened this issue · 7 comments
Hi,
I regularly need to check whether or not something is a primitive type, i.e. a boolean, number, or string. ATM I have to write ugly code like:
if(is.not.boolean(x) && is.not.number(x) && is.not.string(x)) throw new TypeError('...');
It would be great to be able to replace that with:
if(is.not.primitive(x)) throw new TypeError('...');
Assuming it would be accepted, I would be happy to write the code for this and submit a pull request. Would such a request get accepted?
Hi @bbusschots-mu!
Would ! is.object(value)
work for your situation?
@jdalton an interesting idea, but I did a little testing and it is subtly different:
$ node
> const is = require('is_js');
undefined
> is.not.object(function(){})
false
> is.not.object([])
false
> is.not.object("")
true
> is.not.object(42)
true
> is.not.object(true)
true
> is.not.object(NaN)
true
> is.not.object(null)
true
> typeof null
'object'
As you can see, everything went as expected until I tried with null
. null
is not a primitive, so it should return false. (Also, null
is an object, so have I just found a bug?)
null
is a primitive. It's the non-object value as undefined
is the non-value value.
@jdalton I guess you can argue it's a primitive, but it is definitely an object, so should is.object(null)
not return true
?
I know this is going to read odd but typeof
does not necessarily dictate a value's type. null
is not an object and not considered one by the specification. You can see this in builtins by doing:
Object.defineProperty(null, 'a', {value:1 })
// throws Uncaught TypeError: Object.defineProperty called on non-object
@jdalton odd indeed — but I see your point.
I guess it comes down purely to supporting a more human-friendly coding style in two particular ways:
Most obviously, I think this the intent of is.not.object()
is less clear than the intent of is.primitive()
.
But less obviously, needing to rely on the .not
interface means you can't check arrays without reverting to the !
operator, which is definitely much less human-friendly code. is.all.primitive()
is much clearer than !is.any.object()
.
@jdalton are you running this project now? I'd be interested in writing some more features like this, I'd quit before since the creator didn't seem to want to work on it.