Skip to content

Instantly share code, notes, and snippets.

@Tahseenm
Created November 5, 2017 00:39
Show Gist options
  • Save Tahseenm/132b49d7779e0fbb10a94b930581f182 to your computer and use it in GitHub Desktop.
Save Tahseenm/132b49d7779e0fbb10a94b930581f182 to your computer and use it in GitHub Desktop.
A better checking for type of a value in javascript
const capitalise = word =>
word[0].toUpperCase() + word.slice(1).toLowerCase()
/** (val: any) -> string */
const typeOf = val => {
if (val === null) return 'null'
if (val === void val) return 'undefined'
if (Number.isNaN(val)) return 'NaN'
if (Array.isArray(val)) return 'Array'
if (RegExp.prototype.isPrototypeOf(val)) return 'RegExp'
return capitalise(typeof val)
}
/**
* Example
*/
console.log( typeof undefined ) // -> 'undefined'
console.log( typeof null ) // -> 'object' :(
console.log( typeof NaN ) // -> 'number' :(
console.log( typeof 1 ) // -> 'number'
console.log( typeof 'abc' ) // -> 'string'
console.log( typeof true ) // -> 'boolean'
console.log( typeof Symbol(0) ) // -> 'symbol'
console.log( typeof {} ) // -> 'object'
console.log( typeof [] ) // -> 'object' :(
console.log( typeof /abc/g ) // -> 'object' :(
console.log( typeOf(undefined) ) // -> 'undefined'
console.log( typeOf(null) ) // -> 'null' :)
console.log( typeOf(NaN) ) // -> 'NaN' :)
console.log( typeOf(1) ) // -> 'Number'
console.log( typeOf('abc') ) // -> 'String'
console.log( typeOf(true) ) // -> 'Boolean'
console.log( typeOf(Symbol(0)) ) // -> 'Symbol'
console.log( typeOf({}) ) // -> 'Object'
console.log( typeOf([]) ) // -> 'Array' :)
console.log( typeOf(/abc/g) ) // -> 'RegExp' :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment