JavaScript Type checking
I know, I know. You should be doing duck typing and letting things blowup. Or only checking for the specific things you want. And yet I tend to find myself doing a bit of type checking around argument parsing.
Anyway I've had some success with type checking using the parent Object.prototype.toString
with a few special cases. Here's the code I ended up using in my argument parsing library "funs":
function getType(o) {
var rawTypeString =
Object.prototype.toString.call(o);
var typeString =
rawTypeString.replace('[object ', '')
.replace(']', '')
.toLowerCase();
if (typeString === 'number' && Number.isNaN(o)) {
return 'nan';
}
if (o instanceof Error) {
return 'error';
}
if (typeString.indexOf('html') === 0) {
return 'dom';
}
return typeString;
}
Full code in use at: https://github.com/copenhas/funs
Written by Sean Copenhaver
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#