An alternative, safer & cleaner way to compare Types in javascript 1391/11/19

I was never happy with javascript type checking using typeof and comparing the result with a string; as a small spelling error in type name can lead into false results that do not even throw a good error. After a discussion with Afshin Mehrabani (Thank you man!) we thought we can put an end to this. So here is the initial result of that discussion.

function assertType(obj, type) {
    return obj.constructor.name === type.name
}

And now let's test it:

assertType("test", String); //true
assertType(1, String); //false
assertType(1, Number); //true
 
function Book(){};
function Desk(){};
var book = new Book();
assertType(book, Book); //true
assertType(book, Desk); //false

assertType([], Array); //true
assertType(function(){}, Function); //true

And compare it with the traditional "typeof" method. as you may know it has shortcomings with objects and arrays

typeof "test" === "string"; //true
typeof 1 === "string"; //false
typeof 1 === "number"; //true
typeof book === "object"; //true. but we can not compare it with its constructor type. bad!

Not bad at all Huh? You may ask Is it fast enough as typeof? No, I mean not at all. Is it elegant and less error pron than comparing types with strings? Yes, and a big YES! Even you get a great error while that type is misspelled and actully does not exists. I think most of us can live with its low speed as long as we wouldn't need very faster type checking than ~ 1,782,000 checks per second!

Comments

Harry Clarke — 2014-09-12
In IE (11 at least) doesn't give functions name values, which makes breaks this method, unfortunately, in a way which can go undetected (obj.constructor.name and type.name are both undefined).
A quick check to see if type.name is undefined can allow you to use the old method when IE inevitably fails.

Any thoughts? Please leave a reply

I'll use your email to show your picture using gravatar. I hate spam too.
Back to home

I'm Arash Milani, hacker & happiness ninja.
@narmand is our teams's lab to experiment awesome things in it.

I write and talk about hacking, developing web apps, teamwork and designing for better user experience.

You can always contact me via me[at]arashmilani.com email address.