Skip to content

Instantly share code, notes, and snippets.

@arashmilani
Created February 7, 2013 17:13
Show Gist options
  • Save arashmilani/4732488 to your computer and use it in GitHub Desktop.
Save arashmilani/4732488 to your computer and use it in GitHub Desktop.
Trying to find much better way to assert Types in javascript rather than comparing types in string using typeof
function assertType(obj, type) {
return obj.constructor.name === type.name
}
console.info(assertType("test", String)); //true
console.info(assertType(1, String)); //false
console.info(assertType(1, Number)); //true
function Book(){};
function Desk(){};
var book = new Book();
console.info(assertType(book, Book)); //true
console.info(assertType(book, Desk)); //false
console.info(assertType([], Array)); //true
console.info(assertType(function(){}, Function)); //true
@miladr
Copy link

miladr commented Feb 7, 2013

var testObj=new Object();
console.info(assertType(testObj, Object)); //True

@miladr
Copy link

miladr commented Feb 7, 2013

console.info(assertType({}, Object)); //True

@arashmilani
Copy link
Author

Note that there's NO WAY to beat "typeof" in performance.
Check it here for yourself: http://jsperf.com/am-type-assertion#run

@afshinm
Copy link

afshinm commented Feb 7, 2013

Geeks, here the updated gist with prototype: https://gist.github.com/afshinm/4733756

@arashmilani
Copy link
Author

Thank you Afshin for the prototype version :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment