type-name

Just a reasonable typeof

type-name

Just a reasonable typeof

typeName function returns reasonable type name for input value.

descriptioninputresult
string literal'foo''string'
number literal5'number'
boolean literalfalse'boolean'
regexp literal/^not/'RegExp'
array literal['foo', 4]'Array'
object literal{name: 'bar'}'Object' (be careful!)
function expressionfunction () {}'function'
String objectnew String('foo')'String'
Number objectnew Number('3')'Number'
Boolean objectnew Boolean('1')'Boolean'
Date objectnew Date()'Date'
RegExp objectnew RegExp('^not', 'g')'RegExp'
Array objectnew Array()'Array'
Object objectnew Object()'Object'
Function objectnew Function('x', 'y', 'return x + y')'function' (be careful!)
Error objectnew Error('error!')'Error'
NaNNaN'number'
InfinityInfinity'number'
MathMath'Math'
JSON (IE8+)JSON'JSON'
arguments object (IE9+)(function(){ return arguments; })()'Arguments'
null literalnull'null'
undefined valueundefined'undefined'
User-defined constructornew Person('alice', 5)'Person'
Anonymous constructornew AnonPerson('bob', 4)''
var typeName = require('type-name'),
    assert = require('assert');
 
assert(typeName('foo') === 'string');
assert(typeName(5) === 'number');
assert(typeName(false) === 'boolean');
assert(typeName(/^not/) === 'RegExp');
assert(typeName(['foo', 4]) === 'Array');
assert(typeName({name: 'bar'}) === 'Object');
assert(typeName(function () {}) === 'function');
assert(typeName(new String('foo')) === 'String');
assert(typeName(new Number('3')) === 'Number');
assert(typeName(new Boolean('1')) === 'Boolean');
assert(typeName(new Date()) === 'Date');
assert(typeName(new RegExp('^not', 'g')) === 'RegExp');
assert(typeName(new Array()) === 'Array');
assert(typeName(new Object()) === 'Object');
assert(typeName(new Function('x', 'y', 'return x + y')) === 'function');
assert(typeName(new Error('error!')) === 'Error');
assert(typeName(NaN) === 'number');
assert(typeName(Infinity) === 'number');
assert(typeName(Math) === 'Math');
assert(typeName(JSON) === 'JSON'); // IE8+ 
assert(typeName((function(){ return arguments; })()) === 'Arguments');  // IE9+ 
assert(typeName(null) === 'null');
assert(typeName(undefined) === 'undefined');
 
function Person(nameage) {
    this.name = name;
    this.age = age;
}
 
var AnonPerson = function(nameage) {
    this.name = name;
    this.age = age;
};
 
assert(typeName(new Person('alice', 5)) === 'Person');
assert(typeName(new AnonPerson('bob', 4)) === '');

Install

$ npm install --save type-name

Use

var typeName = require('type-name');
console.log(typeName(anyVar));

Install

$ bower install --save type-name

Load (typeName function is exported)

<script type="text/javascript" src="./path/to/bower_components/type-name/build/type-name.js"></script>

Use

console.log(typeName(anyVar));

Install and build

$ component install twada/type-name
$ component build

Then use as usual.

Licensed under the MIT license.