Skip to content

Instantly share code, notes, and snippets.

@arashmilani
Created February 7, 2013 17:13
Show Gist options
  • Select an option

  • Save arashmilani/4732488 to your computer and use it in GitHub Desktop.

Select an option

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

miladr commented Feb 7, 2013

Copy link
Copy Markdown

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

@miladr

miladr commented Feb 7, 2013

Copy link
Copy Markdown

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

@arashmilani

Copy link
Copy Markdown
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

afshinm commented Feb 7, 2013

Copy link
Copy Markdown

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

@arashmilani

Copy link
Copy Markdown
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